Page 394 - Computer Science V2.0 Class 11
P. 394
>>> lst.remove(20)
>>> lst
[10, 30, 10, 50, 20, 60, 20, 30, 55]
>>> lst.remove(66)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
lst.remove(66)
ValueError: list.remove(x): x not in list
● lst.pop(index): The method removes the element from the specified index and returns the element
removed from the list. If the index is omitted, the rightmost element is returned. For example,
>>> lst = [10, 20, 30, 10, 50, 20, 60, 20, 30, 55]
>>> lst.pop(3)
10
>>> lst
[10, 20, 30, 50, 20, 60, 20, 30, 55]
>>> lst.pop()
55
>>> lst
[10, 20, 30, 50, 20, 60, 20, 30]
● del statement: The del statement can also be used to remove an element from the list by specifying its index.
>>> lst = [10, 20, 30, 10, 50, 20, 60, 20, 30, 55]
>>> del lst[3]
>>> lst
[10, 20, 30, 50, 20, 60, 20, 30, 55]
Delete a Slice: You can also use the del statement to remove a slice of elements from the list.
myList = [10, 20, 30, 40, 50]
del myList[1:4] # Removes elements at index 1, 2, and 3 (20, 30, 40)
print(myList) # Output: [10, 50]
Delete Entire List: If you want to completely remove the entire list and free up the memory it occupies, you can use
the del statement without specifying an index.
myList = [10, 20, 30]
del myList # Deletes the entire list
# Now myList is not defined and will raise an error if used
The built-in functions for list manipulations are summarized in the following table:
Table 13.2: Built-in functions for list manipulations
Method Description Example
lst.append(elem) Inserts the object elem, passed as an >>>list_l1=['Touchpad',
argument, at the end of the list. 'Computer', 'Science']
>>>list_l1.append(35)
['Touchpad', 'Computer',
'Science', 35]
lst. Inserts the object elem, passed as an >>>list_l1=['Touchpad',
insert(index, argument, at the specified index. 'Computer', 'Science']
elem) >>>list_l1.append(2,35)
['Touchpad', 'Computer', 35,
'Science']
380 Touchpad Computer Science (Ver. 2.0)-XI

