Page 258 - Ai_V1.0_Class9
P. 258
For example,
Commands Output
vowels=['a', 'e', 'i', 'o', 'u'] i
val=vowels.pop(2)
print(val)
vowels=['a', 'e', 'i', 'o', 'u'] u
val=vowels.pop()
print(val)
vowels=['a', 'e', 'i', 'o', 'u'] IndexError: pop index out of range
val=vowels.pop(6)
print(val)
lst=[] IndexError: pop from empty list
lst.pop()
Some other Functions Used with List
There are some other functions also available to use with the list which are as follows:
• len(): This function returns the length of a list. For example,
marks = [10, 34, 42, 21, 45]
print(len(marks))
Output: 5
• clear(): This function removes all the elements of the list in one go. It empties the list but the empty list still
exists in Python which can be used later to fill the values. For example,
city=["Delhi", "Mumbai", "Kolkata", "Chennai"]
city.clear()
print(city)
Output: [ ]
• reverse(): This function reverses the content of the list "in place". For example,
alpha = ['a', 'b', 'c', 'd', 'e']
alpha.reverse()
print(alpha)
Output: ['e', 'd', 'c', 'b', 'a']
• sort(): This function sorts the list in ascending or descending order. This is done "in the list itself" and works for
the list with values of the same data types. For example,
city=["Delhi", "Mumbai", "Kolkata", "Chennai"]
city.sort() #sorts the list by default in ascending order
print(city)
Output: ["Chennai", "Delhi", "Kolkata", "Mumbai"]
city.sort(reverse=True)#sorts the list descending order
Output: ["Mumbai", "Kolkata", "Delhi", "Chennai"]
256 Artificial Intelligence Play (Ver 1.0)-IX

