The pop method
The pop method removes and returns an element from the list by its index. In the method parameter, we specify the index of the element. If it is not specified, the last element is returned.
Syntax
list.pop([index index number subject-heading ind.])
Example
Let's remove the last element:
lst = ['a', 'b', 'c', 'd', 'e']
lst.pop()
print(lst)
Result of code execution:
['a', 'b', 'c', 'd']
Example
The method returns the removed element:
lst = ['a', 'b', 'c', 'd', 'e']
print(lst.pop())
Result of code execution:
'e'
Example
Let's find an element by index and remove it using the pop method:
lst = ['a', 'b', 'c', 'd', 'e']
lst.pop(2)
print(lst)
Result of code execution:
['a', 'b', 'd', 'e']
Example
Now let's try to remove an element by index that is not in the list:
lst = ['a', 'b', 'c']
lst.pop(3)
Result of code execution:
IndexError: pop index out of range
See also
-
method
remove,
which removes an element from a list -
method
insert,
which adds an element to the list before the specified index -
method
count,
which returns the number of times an element occurs in a list -
method
append,
which adds an element to the end of a list -
function
len,
which returns the length of the list