Page 296 - Computer Science Class 11 Without Functions
P. 296
12.8 List Methods
Python provides several methods to manipulate lists. Below, we will discuss some of these methods with an example
list: lst. These methods do not create a new list; they modify the original list: lst. Such an operation that takes place
on an existing object is said to be in place.
● lst.append(elem): The method append() inserts the object elem, passed as an argument, at the end of
the list lst.
Example:
>>> lst1 = [10, 20, 30, 40]
>>> lst1.append(35)
>>> lst1
[10, 20, 30, 40, 35]
● lst.insert(index, elem): The method insert() inserts the object elem, passed as an argument, at the
specified index.
Example:
>>> names = ['Aryan', 'Anthony', 'Sunpreet', 'Venkatesh']
>>> names.insert(2, 'Samantha')
>>> names
['Aryan', 'Anthony', 'Samantha', 'Sunpreet', 'Venkatesh']
● lst.extend(obj): The method extend() inserts the elements in obj, passed as an argument, at the end of the
elements of the list lst. Note that obj may not necessarily be a list and could as well be a tuple, set, or dictionary.
Example:
>>> intList = [10, 20, 30]
>>> intList.extend([40,50])
>>> intList
[10, 20, 30, 40, 50]
C T 02 Assuming that lst is a list, what is the difference between the operations?
lst.extend([40,50]) and lst + [40, 50]
>>> 1st = [1, 2, 3]
>>> 1st.extend([4, 5])
>>> 1st
[1, 2, 3, 4, 5]
>>> 1st = [1, 2, 3]
>>> 1st + [4, 5]
[1, 2, 3, 4, 5]
>>> 1st
[1, 2, 3]
● lst.index(elem): The method index() returns the index of the first occurrence of the element elem in the
list. If elem does not appear in the list lst, it throws a ValueError, for example,
>>> names = ['Aryan', 'Anthony', 'Samantha', 'Sunpreet', 'Venkatesh']
>>> names.index('Samantha')
2
>>> name = 'Arjun'
>>> names.index(name)
Traceback (most recent call last):
File '<pyshell#3>', line 1, in <module>
names.index(name)
ValueError: 'Arjun' is not in list
Note: To avoid ValueError, we can use the membership operator to check the membership of an element.
294 Touchpad Computer Science-XI

