pop() method in a python list is used to remove an element from a list by index.
pop() takes a numeric argument and removes the list element at this index.

Remember that elements in a list are ordered by numeric indexes with the index of first element from left 0, second element as 1 and so on.

Also, the index of first element from the right is -1, second from right -2, etc. as shown in the below illustration.element indexing in python listpop() syntax
Syntax of pop() method is

element = pop(index)

pop() returns the element that it removes from the list.

pop() removes the element based on following argument values.

  • If the argument is positive, then the element is removed from left since it assumes that the index needs to be counted from left.
  • If the argument is negative, then the element is removed from right since it assumes that the index needs to be counted from right.
  • If no index is given, then pop() considers it -1 by default. This means that the last element is removed.
  • If the index is out of range or the list is empty, then IndexError is raised.

pop() example
Examples of pop() method are given below.

# create a list
numbers = [ 2, 4, 8, 10, 15]
print('Original list:',numbers)
# pop third element
element = numbers.pop(2)
print('Element removed is:',element)
print('Remaining list is',numbers) 

# pop second last element
element = numbers.pop(-2)
print('Element removed is:',element)
print('Remaining list is',numbers)

# pop without argument
element = numbers.pop()
print('Element removed is:',element)
print('Remaining list is',numbers)

# pop with invalid index
numbers.pop(10)

Above code snippet creates a list and invokes pop() on the list multiple times.

  • First time with 2, which removes the third element from the left.
  • Second time with -2, which removes the second element from the right.
  • Third with no argument, which removes the last list element.

Finally, with an index that exceeds the length of the list. This should be an error.

Output of above example is

Original list: [2, 4, 8, 10, 15]

Element removed is: 8

Remaining list is: [2, 4, 10, 15]

Element removed is: 10

Remaining list is: [2, 4, 15]

Element removed is: 15
Remaining list is: [2, 4]

numbers.pop(10)
IndexError: pop index out of range

Look at the last error message since we tried to remove an element at position 11 which is less than the size of the list.

This article demonstrated the usage of pop() to remove a list item but there are other methods to remove an element from a list.

Leave a Reply