Python list pop() method

Introduction to python list pop():

Python list pop method is used to remove and return item from a list. This method can be used to remove an item by providing the index of it or without providing the index.

In this post, we will learn how to use pop with different examples.

Definition of list pop():

The list pop method is defined as below:

list.pop()

list.pop(index)

If we use the index, it removes the item at that index and returns it. If we don’t provide the index, it removes the last element of the list and returns it.

Example of list pop():

Let’s take a look at the below example:

given_list = [1, 2, 3, 4, 5]

removed_item = given_list.pop(2)
print('Removed item is {} and list changed to {}'.format(removed_item, given_list))

removed_item = given_list.pop()
print('Removed item is {} and list changed to {}'.format(removed_item, given_list))

Here,

  • We used pop() two times. The first time, it removed the item at index 2 and second time it is not using the index.

It will print the below output:

Removed item is 3 and list changed to [1, 2, 4, 5]
Removed item is 5 and list changed to [1, 2, 4]

As you can see here, pop() removes an item from a list and returns it.

You might also like: