Page 415 - Ai_417_V3.0_C9_Flipbook
P. 415
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"]
• index(): It returns the index number of the value given in the function. For example,
city=["Delhi", "Mumbai", "Kolkata", "Chennai"]
print (city.index("Kolkata"))
Output: 2
print (city.index("Pune"))
Output: ValueError: 'Pune' is not in list
It returns ValueError exception if the value is not found in the list.
• count(): This function counts the number of occurrences of the specified value in the given list. If the value
doesn't exist, then the function returns 0. For example,
marks = [56, 67, 45, 78, 56, 78, 12]
marks.count(78)
Output: 2
marks.count(10) # 10 does not exist in the list.
Output: 0
Introduction to Python 413

