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

list.pop([index])
  • 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

  1. Popping the Last Item:

    my_list = [1, 2, 3, 4] last_item = my_list.pop() # Removes and returns the last item (4) print(last_item) # Output: 4 print(my_list) # Output: [1, 2, 3]
  2. Popping an Item by Index:

    my_list = ['a', 'b', 'c', 'd'] second_item = my_list.pop(1) # Removes and returns the item at index 1 ('b') print(second_item) # Output: 'b' print(my_list) # Output: ['a', 'c', 'd']
  3. Using Negative Index: You can use negative indexing to pop items from the end of the list:

    my_list = [10, 20, 30, 40] item = my_list.pop(-2) # Removes and returns the second last item (30) print(item) # Output: 30 print(my_list) # Output: [10, 20, 40]
  4. Popping from an Empty List: Attempting to pop from an empty list will raise an IndexError:

    empty_list = [] try: empty_item = empty_list.pop() # Attempting to pop from an empty list except IndexError as e: print(e) # Output: pop from empty list
  5. Using pop() in a Loop: You can use pop() in a loop to remove all items from a list one by one:

    my_list = [1, 2, 3] while my_list: print(my_list.pop()) # Prints and removes items until the list is empty # Output: 3, 2, 1 (in this order)

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.