The list pop() method removes and returns the item at a specified index. If no index is specified, pop() removes and returns the last item. Here's a quick example:
models = ['Claude', 'ChatGPT', 'Gemini', 'ChatGPT']
item = models.pop()
print(f'Removing last item: {item}')
item = models.pop(2)
print(f'Removing item at index 2: {item}')
Output
Removing last item: ChatGPT Removing item at index 2: Gemini
pop() Syntax
The syntax of pop() is:
item = my_list.pop(index)
Arguments
The method takes a single argument, the index of the item to be removed. If omitted, index defaults to -1 (index of the last item).
Return Value
It returns the item at the specified index (or the last item if index is omitted). This item is also removed from the list.
Example: pop() with Different Indices
vowels = ['a', 'e', 'i', 'o', 'u']
item = vowels.pop()
print(f'Item removed: {item}')
print(f'Current list: {vowels}')
item = vowels.pop(-3)
print(f'Item removed: {item}')
print(f'Current list: {vowels}')
Output
Item removed: u Current list: ['a', 'e', 'i', 'o'] Item removed: i Current list: ['a', 'e', 'o']
Example: Passing Index that Doesn't Exist to pop()
If we use an index that is outside the list's range, pop() raises IndexError.
vowels = ['a', 'e', 'i', 'o', 'u']
item = vowels.pop(6)
print(f'Item removed: {item}')
print(f'Current list: {vowels}')
Output
IndexError: pop index out of range
Using pop() for Creating a Stack
Since pop() removes items from the end, makes it really easy to implement a stack data structure (Last In, First Out) when combined with append().
stack = []
stack.append(1) # push
stack.append(2) # push
stack.append(3) # push
print(stack.pop()) # 3
print(stack.pop()) # 2
Here's how the above implementation of stack works:
Also Read:
- Python List remove() - Remove the specified item.