Monday, December 26, 2016

Lists in Python : Practice 3


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)
['algo', 'ds', 'ai', 'web', 'nw', 'db']

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"))
2
5
In [3]:
# find doesn't work in lists.
print(list.find("algo")) # doesn't work
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-3-248a9ca5daad> in <module>()
      1 # find doesn't work in lists.
----> 2 print(list.find("algo")) # doesn't work

AttributeError: 'list' object has no attribute 'find'
In [4]:
#index works both in strings and lists
print(a.index("pr"))
5

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)
['algo', 'ds', 'ai', 'web', 'nw', 'db', 'graphics']
In [6]:
list.insert(3,"datamining")
print(list)
['algo', 'ds', 'ai', 'datamining', 'web', 'nw', 'db', 'graphics']

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)
['algo', 'ds', 'ai', 'datamining', 'web', 'nw', 'db', 'graphics']
['algo', 'ds', 'ai', 'datamining', 'web', 'db', 'graphics']
['ds', 'ai', 'datamining', 'web', 'db', 'graphics']

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)
['ai', 'algo', 'db', 'ds', 'nw', 'web']
In [10]:
list = ["algo","ds","ai","web","nw","db"]
list.sort(reverse = True)
print(list)
['web', 'nw', 'ds', 'db', 'algo', 'ai']
In [11]:
list = ["z","A","Z","a"]
list.sort()
print(list)
['A', 'Z', 'a', 'z']
In [12]:
list = ["z","A","Z","a"]
list.sort(key = str.lower)
print(list)
['A', 'a', 'z', 'Z']

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)
new sorted list  ['ai', 'algo', 'db', 'ds', 'nw', 'web']
sorted_list  ['algo', 'ds', 'ai', 'web', 'nw', 'db']
sorted function doesn't change the list. It just creates a new list.
In [ ]:
 

No comments :

Post a Comment