Page 345 - Computer Science Class 11 With Functions
P. 345
● 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]
>>> 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
13.6.1 Creating a Sorted List
The function sorted returns a sorted list comprising the elements of the list passed as argument, but without
modifying it.
>>> lst = ['Physics', 'Chemistry', 'Maths', 'Computer Sc.']
>>> sorted(lst)
['Chemistry', 'Computer Sc.', 'Maths', 'Physics']
>>> lst
['Physics', 'Chemistry', 'Maths', 'Computer Sc.']
13.6.2 Quick Programming Question
Write a function to count the frequency of each element in a list. Make use of it to write a program that accepts a list
of integers and displays the frequency of each element in the list.
Lists and Tuples 343

