Page 414 - Ai_417_V3.0_C9_Flipbook
P. 414
The remove( ) Function
The remove() function removes the first occurrence of the element with the specified value. It means only one
value can be removed at a time even if there are duplicate values in the list. If you wish to remove multiple values
then this function can be used within a loop where it repeats itself a specific number of times. The syntax of the
remove() function is:
list.remove(<single value>)
For example,
Commands Output
marks = [23, 34, 23, 45, 56, 78, 56] [34, 23, 45, 56, 78, 56]
marks.remove(23)
print(marks)
marks = [23, 34, 23, 45, 56, 78, 56] [23, 34, 23, 45, 78, 56]
marks.remove(56)
print(marks)
marks = [23, 34, 23, 45, 56, 78, 56] ValueError: list.remove(x): x not in list
marks.remove(72)
print(marks)
The pop( ) Function
The pop() function removes an element from the list based on the index number specified in the function and
returns the deleted value. In case no index number is given then by default it removes the last element from the
list. If we try to remove an index number which does not exist then it gives an IndexError.
For example,
Commands Output
vowels=['a', 'e', 'i', 'o', 'u'] i
val=vowels.pop(2)
print(val)
vowels=['a', 'e', 'i', 'o', 'u'] u
val=vowels.pop()
print(val)
vowels=['a', 'e', 'i', 'o', 'u'] IndexError: pop index out of range
val=vowels.pop(6)
print(val)
lst=[] IndexError: pop from empty list
lst.pop()
Some other Functions Used with List
There are some other functions also available to use with the list which are as follows:
• len(): This function returns the length of a list. For example,
marks = [10, 34, 42, 21, 45]
print(len(marks))
412 Touchpad Artificial Intelligence (Ver. 3.0)-IX

