Methods in Python¶
Methods are the functions which can be attached are called on a certain value.
In [1]:
list = ["algo","ds","ai","web","nw","db"]
print(list)
index , find method.¶
index method is used to find the index position of a value in a list. find method is used to find the position of a substring in a string.
In [2]:
print(list.index("ai"))
a = "arun prakash"
print(a.find("pr"))
In [3]:
# find doesn't work in lists.
print(list.find("algo")) # doesn't work
In [4]:
#index works both in strings and lists
print(a.index("pr"))
append vs insert method¶
append : It adds the value to the end of the list insert: It adds the value to the given position in a list Let's add "graphics" using append method, and add "datamining" in position 3 in the list using index method
In [5]:
list.append("graphics")
print(list)
In [6]:
list.insert(3,"datamining")
print(list)
remove and del method¶
remove method takes a list value and remove it from the list. del method takes the index position and deletes from the list
In [7]:
print(list)
list.remove("nw")
print(list)
del list[0]
print(list)
sort method¶
Sort method is used to sort the values either ascending or descending order. It compares using ascii values and sort. We cannot sort a list containing both intergers and strings.
In [9]:
list = ["algo","ds","ai","web","nw","db"]
list.sort()
print(list)
In [10]:
list = ["algo","ds","ai","web","nw","db"]
list.sort(reverse = True)
print(list)
In [11]:
list = ["z","A","Z","a"]
list.sort()
print(list)
In [12]:
list = ["z","A","Z","a"]
list.sort(key = str.lower)
print(list)
sorted function¶
Sorted is a function, not a method. It takes a list and return a new sorted list.
In [13]:
sorted_list = ["algo","ds","ai","web","nw","db"]
new_sorted_list = sorted(sorted_list)
print("new sorted list ", new_sorted_list)
print("sorted_list ",sorted_list)
sorted function doesn't change the list. It just creates a new list.
In [ ]:
No comments :
Post a Comment