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 this function with a practical example. The syntax of the Python pop list method is

listname.pop(index_value)

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

Python List pop example

The Python list pop method 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 position 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 pop method to remove items at index positions 1 and 2.

Python Pop List Function 2

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

It is an another example of this method on 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']

Python Program to Remove List Items

This program deletes nested items at the index position 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]]