List pop() Method in Python

Python List pop() Method

In Python, the pop() method is used to remove and return an element from a list at a specified index. It is a built-in method available for lists in Python.

Syntax of the pop() method:

popped_element = list_name.pop(index)
  • list_name: This is the name of the list from which you want to remove the element.
  • index: (optional) This is the index of the element you want to remove. If the index is not provided, the method will remove and return the last element of the list.

The pop() method removes the specified element from the list and returns that element. If you provide an index, it removes the element at that index. If no index is provided, it removes the last element.

Example 1:

# Create a list
numbers = [10, 20, 30, 40, 50]

# Remove and return the element at index 2 (which is 30)
popped_element = numbers.pop(2)

print(popped_element)  # Output: 30
print(numbers)         # Output: [10, 20, 40, 50]

Example 2:

# Create a list
fruits = ['apple', 'banana', 'orange']

# Remove and return the last element ('orange')
popped_element = fruits.pop()

print(popped_element)  # Output: 'orange'
print(fruits)          # Output: ['apple', 'banana']

Example 3:

# Create a list
my_list = [1, 2, 3]

# Try to remove and return an element at index 10 (which is out of range)
try:
    popped_element = my_list.pop(10)
    print(popped_element)
except IndexError:
    print("Index out of range.")

# Output: Index out of range.

As you can see, the pop() method is useful when you need to remove an element from a specific index or the last element of a list, and it allows you to retrieve the removed element as well. If you try to pop() an index that is out of range (not present in the list), it will raise an IndexError.