Page 393 - Computer Science V2.0 Class 11
P. 393
>>> if name in names:
... names.index(name)
... else:
... print(name, "doesn't exist in the list")
Arjun doesn't exist in the list
● lst.count(element): The method count() returns the number of times an element elem appears in a
list. For example,
>>> fruits = ['apple', 'banana', 'orange', 'banana', 'kiwi']
>>> countOccurrence = fruits.count('banana')
>>> print(countOccurrence)
>>> 2
In this example, we have a list of fruits that contains multiple occurrences of the string 'banana'. We use the
count() method to count the number of times 'banana' appears in the list and store the result in the variable
countOccurrence. The print() function then outputs the value of countOccurrence, which is 2.
Note that the count() method only counts the occurrences of a single element in the list. If you want to count the
occurrences of multiple elements in the list, you must call the count() method separately for each element. Also,
note that the count() method returns 0 if the element is not present in the list.
● lst.reverse(): The method reverse reverses the order of the elements in the list, for example,
>>> names = ['Aryan', 'Anthony', 'Samantha', 'Sunpreet', 'Venkatesh']
>>> names.reverse()
>>> names
['Venkatesh', 'Sunpreet', 'Samantha', 'Anthony', 'Aryan']
● lst.sort(): The method arranges the elements of the list in the ascending order.
Example:
>>> names.sort()
>>> names
['Anthony', 'Aryan', 'Samantha', 'Sunpreet', 'Venkatesh']
To sort the elements in a list, in descending order, we set the argument reverse = True, as shown below:
>>> names = ['Aryan', 'Anthony', 'Samantha', 'Sunpreet', 'Venkatesh']
>>> names.sort(reverse = True)
>>> names
['Venkatesh', 'Sunpreet', 'Samantha', 'Aryan', 'Anthony']
When the argument key=function is specified, the function is applied to each element of the list, and the
values in the list are arranged according to the ascending order of the function values. For example, we define a
function f(x) which returns 1/x.
>>> def f(x): x
... return 1/x
>>> 1st = [4, 16, 10, 2]
>>> 1st.sort(key=f)
>>> 1st
[16, 10, 4, 2]
Applying the function f to the elements 4, 16, 10, 2 of lst yields the numbers 1/4, 1/16, 1/10, 1/2. An ascending
order listing of these numbers would be 1/16, 1/10, 1/4, 1/2. As this listing of numbers corresponds to the numbers
16, 10, 4, and 2, respectively, on sorting the list (lst) according to the function values of its elements, we get the
list [16, 10, 4, 2].
● lst.remove(element): The method remove(element) searches for the first instance of the element
in the list lst and removes it. If an element is not found in lst, the method remove throws a ValueError.
>>> lst = [10, 20, 30, 10, 50, 20, 60, 20, 30, 55]
Lists and Tuples 379

