Python list.pop() function
The list.pop()
method in Python is used to remove and return an item from a list at a specified index. If no index is specified, it removes and returns the last item in the list. This method modifies the original list in place.
Syntax
- Parameters:
index
(optional): The position of the item to be removed. This is zero-based indexing. If not provided, the default is-1
, which refers to the last item in the list.
Return Value
- The method returns the item that has been removed from the list. If the list is empty and you try to pop an item, it raises an
IndexError
.
Example Usage
Popping the Last Item:
Popping an Item by Index:
Using Negative Index: You can use negative indexing to pop items from the end of the list:
Popping from an Empty List: Attempting to pop from an empty list will raise an
IndexError
:Using
pop()
in a Loop: You can usepop()
in a loop to remove all items from a list one by one:
Summary
list.pop([index])
is a versatile method for removing and retrieving items from a list.- It can be used to access elements at specific positions, including the last element by default.
- This method modifies the original list and raises an
IndexError
if you try to pop from an empty list or if the specified index is out of range.