Site icon codippa

Python list pop() method with example

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.pop() 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.

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.

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.

Exit mobile version