The pop() list is a built-in Python method that deletes an element by a specified position. It will print out a new list without the deleted elements. If you don't specify the position, it will remove the last element. If you specify a position out of range, it will return IndexError.
Here at Ibmi Media, we shall look into how to use the pop() method in Python.
The list pop() method will remove the element at the position you want to remove.
If you don't specify the position, it will remove the last element.
It's syntax is given below:
list.pop(pos)
List pop() Method Parameter Values:
pos: the position you want to remove
1. Take a look at the below function:
list = [1, 2, 3, 4]
list.pop(1)
print(list)
The Output will display:
[1, 3, 4]
2. Remove the last element:
list = [1, 2, 3, 4]
list.pop()
print(list)
The Output will display:
[1, 2, 3]
3. Remove the first element:
list = [1, 2, 3, 4]
#I remove the 1st element
list.pop(0)
print(list)
The Output will display:
[2, 3, 4]
4. IndexError:
list = [1, 2, 3, 4]
list.pop(5)
print(list)
The Output will display:
IndexError: pop index out of range
This article covers how to use the pop() method in Python. In fact, the pop() method removes the item at the given index from the list and returns the removed item.
pop() function parameters:
Return Value from pop()
The pop() method returns the item present at the given index. This item is also removed from the list.