The List pop() method removes a single item of the at specified index and returns it.
Syntax
my_list.pop(index)pop() Parameters
Python List pop() method parameters::
| Parameter | Condition | Description |
|---|---|---|
index |
Optional | An index of item you want to remove. Default value is -1 |
pop() Return Value
Python List pop() method returns the item removed at the given index.
Examples
Example 1: Remove an Element at the given index from a List with pop()
The pop() method removes an element in a specified position.
names = ['Tom', 'Anna', 'David', 'Ryan']
removed = names.pop(0) # remove first element from the list
print(names) # Output: ['Anna', 'David', 'Ryan']
print(removed) # Output: Tomoutput
['Anna', 'David', 'Ryan']
TomExample 2: Remove an Element with Negative Index
You can also use negative indexing with pop() method.
names = ['Tom', 'Anna', 'David', 'Ryan']
removed = names.pop(-3) # negative index
print(names) # Output: ['Tom', 'David', 'Ryan']
print(removed) # Output: Annaoutput
['Tom', 'David', 'Ryan']
AnnaExample 3: Remove an Element without an index
When you don't specify the index on pop(), the default value -1 is used and so it removes the last item.
names = ['Tom', 'Anna', 'David', 'Ryan']
removed = names.pop() # use default value -1
print(names) # Output: ['Tom', 'Anna', 'David']
print(removed) # Output: Ryanoutput
['Tom', 'Anna', 'David']
RyanExample 4: Remove an Element with Index Out of Bound
If the index passed to the pop() method is not in range, it throws IndexError (pop index out of range exception).
names = ['Tom', 'Anna', 'David', 'Ryan']
removed = names.pop(10)output
Traceback (most recent call last):
File "main.py", line 2, in <module>
removed = names.pop(10)
IndexError: pop index out of rangeA possible safe solution is to check if the index to pop is inside the bounds:
my_list = [1, 2, 3, 4, 5]
index_to_pop = 5 # This index is out of range
if 0 <= index_to_pop < len(my_list):
popped_item = my_list.pop(index_to_pop)
print("Popped item:", popped_item)
else:
print("Index out of range. Can not pop from an empty list or an index that does not exist.")
print("List after attempted pop:", my_list)output
Index out of range. Can not pop from an empty list or an index that does not exist.
List after attempted pop: [1, 2, 3, 4, 5]