Home »
Python
Python List pop() Method
By IncludeHelp Last updated : June 20, 2023
Python List pop() Method
The pop() is an inbuilt method of the list class that is used to remove an element at the specified index/position from the list, the method is called with this list (list from which we have to remove an element) and the index is supplied as an argument.
Syntax
The following is the syntax of pop() method:
list_name.pop(index)
Parameter(s):
The following are the parameter(s):
- index – It is an optional parameter, it represents the index in the list, we have to remove the element. If we do not provide the value then it's default value will be -1 that will represent the last item.
Return Value
The return type of this method is the type of the element, it returns the removed element.
Example 1: Use of List pop() Method
# declaring the list
cars = ["BMW", "Porsche", "Audi", "Lexus", "Audi"]
# printing the list
print("cars before pop operations...")
print("cars: ", cars)
# removing element from 2nd index
x = cars.pop(2)
print(x,"is removed")
# removing element from 0th index
x = cars.pop(0)
print(x,"is removed")
# printing the list
print("cars before pop operations...")
print("cars: ", cars)
Output
cars before pop operations...
cars: ['BMW', 'Porsche', 'Audi', 'Lexus', 'Audi']
Audi is removed
BMW is removed
cars before pop operations...
cars: ['Porsche', 'Lexus', 'Audi']
Example 2: Use of List pop() Method
# declaring the list
x = [10, 20, 30, 40, 50, 60, 70]
# printing the list
print("x before pop operations...")
print("x: ", x)
res = x.pop(0) # will remove 0th element
print(res,"is removed")
res = x.pop() # will remove last element
print(res,"is removed")
res = x.pop(-1) # will remove last element
print(res,"is removed")
# printing the list
print("x after pop operations...")
print("x: ", x)
Output
x before pop operations...
x: [10, 20, 30, 40, 50, 60, 70]
10 is removed
70 is removed
60 is removed
x after pop operations...
x: [20, 30, 40, 50]
If the index is out of range, IndexError will return.
Example 3: Use of List pop() Method
# declaring the list
x = [10, 20, 30, 40, 50, 60, 70]
# printing the list
print("x before pop operations...")
print("x: ", x)
res = x.pop(15) # will return an error
print(res," is removed")
# printing the list
print("x after pop operations...")
print("x: ", x)
Output
x before pop operations...
x: [10, 20, 30, 40, 50, 60, 70]
Traceback (most recent call last):
File "main.py", line 10, in <module>
res = x.pop(15) # will return an error
IndexError: pop index out of range