Python List pop Function

Python pop function removes an item from the existing list at a user-specified index. In this section, we discuss how to use it with a practical example, and the syntax of the pop list method is

listname.pop(index_value)

Remember, the Index position starts at 0 and ends at n-1.

Python List pop example

It removes the items at the specified index and displays that element. After eliminating, the remaining values move up to fill the index gap. If we know the Index value and want to see the deleted value, we can use this one to remove the item.

The below code removes items at index positions 1 and 2. You can display the eliminated item by assigning the value to a new variable. For example, the first one, b, returns 20.

a = [10, 20, 30, 40]
print(a)

b = a.pop(1)
print(b)
print(a)

a.pop(2)
print(a)
[10, 20, 30, 40]
20
[10, 30, 40]
[10, 30]

pop first, second

In this example, we declared a string list. Next, we used the method to remove items at index positions 1 and 2.

Python Pop List Function 2

TIP: Please refer to the List article to understand everything about Python and functions.

It is another example of this list pop method on the string to delete the items.

Fruits = ['Apple', 'Orange', 'Grape', 'Banana']

Fruit = Fruits.pop(1)
print(Fruits)
print('Item extracted = ', Fruit)
print('========')

Fruit = Fruits.pop(1)
print(Fruits)
print('Item extracted = ', Fruit)
print('========')

Fruit = Fruits.pop(1)
print(Fruits)
print('Item extracted = ', Fruit)
print('========')
['Apple', 'Grape', 'Banana']
Item extracted =  Orange
========
['Apple', 'Banana']
Item extracted =  Grape
========
['Apple']
Item extracted =  Banana
========

Let me use this function on Mixed. Here, we declared a mix of numbers and words. Next, we used the pop function to remove items at index 2.

MixFr = ['apple',  1, 'Orange', 5, 'Kiwi', 'Mango']
print(MixFr)

MixFr.pop(2)
print(MixFr)
['apple', 1, 'Orange', 5, 'Kiwi', 'Mango']
['apple', 'Orange', 'Kiwi', 'Mango']

Remove List Items

This program deletes nested items at the index positions 2 and 3.

Nested = [[71, 222], [22, 13], [11, 22], [44, 55], [99, 77]]
print(Nested)

Nested.pop(2)
print(Nested)

Nested.pop(3)
print(Nested)
[[71, 222], [22, 13], [11, 22], [44, 55], [99, 77]]
[[71, 222], [22, 13], [44, 55], [99, 77]]
[[71, 222], [22, 13], [44, 55]]