×


Python List pop() Method - Explained with Examples



The pop() list is a built-in Python method that deletes an element by a specified position. It will print out a new list without the deleted elements. If you don't specify the position, it will remove the last element. If you specify a position out of range, it will return IndexError.

Here at LinuxAPT, we shall look into how to use the pop() method in Python.


More about List pop() Method

The list pop() method will remove the element at the position you want to remove.

If you don't specify the position, it will remove the last element.

It's syntax is given below:

list.pop(pos)

List pop() Method Parameter Values:

pos: the position you want to remove


Examples of using List pop() Method

1. Take a look at the below function:

list = [1, 2, 3, 4]
list.pop(1)
print(list)

The Output will display:

[1, 3, 4]


2. Remove the last element:

list = [1, 2, 3, 4]
list.pop()
print(list)

The Output will display:

[1, 2, 3]


3. Remove the first element:

list = [1, 2, 3, 4]
#I remove the 1st element
list.pop(0)
print(list)

The Output will display:

[2, 3, 4]


4. IndexError:

list = [1, 2, 3, 4]
list.pop(5)
print(list)

The Output will display:

IndexError: pop index out of range


[Need help in fixing Python function issues ? We can help you. ]


Conclusion

This article covers how to use the pop() method in Python. In fact, the pop() method removes the item at the given index from the list and returns the removed item.


pop() function parameters:

  • The pop() method takes a single argument (index).
  • The argument passed to the method is optional. If not passed, the default index -1 is passed as an argument (index of the last item).
  • If the index passed to the method is not in range, it throws IndexError: pop index out of range exception.


Return Value from pop()

The pop() method returns the item present at the given index. This item is also removed from the list.


More Linux Tutorials

We create Linux HowTos and Tutorials for Sys Admins. Visit us on IbmiMedia.com

Also for Tech related tips, Visit forum.outsourcepath.com or General Technical tips on www.outsourcepath.com