Removes an item at specified index
Usage
The pop()
method removes a single list item at specified index and returns it. If no index is specified, pop()
method removes and returns the last item in the list.
Syntax
list.pop(index)
Parameter | Condition | Description |
index | Optional | An index of item you want to remove. Default value is -1 |
Return Value
The pop()
method returns the value of removed item.
Examples
# Remove 2nd list item
L = ['red', 'green', 'blue']
L.pop(1)
print(L)
# Prints ['red', 'blue']
You can also use negative indexing with pop()
method.
# Remove 2nd list item
L = ['red', 'green', 'blue']
L.pop(-2)
print(L)
# Prints ['red', 'blue']
When you remove an item from the list using pop()
, it removes it and returns its value.
L = ['red', 'green', 'blue']
x = L.pop(1)
# removed item
print(x)
# Prints green
When you don’t specify the index on pop()
, it assumes the parameter to be -1 and removes the last item.
L = ['red', 'green', 'blue']
L.pop()
print(L)
# Prints ['red', 'green']