Python List pop function is one of the List functions, which removes an item from the existing list at a user-specified index. In this section, we discuss how to use this Python pop function with a practical example.
The syntax of the Python list pop function is
list_name.pop(index_value)
Remember, the Index position starts at 0 and ends at n-1.
Python List pop example
The below code removes items at index position 1 and 2. You can display the removed item by assigning the value to a new variable. For example, b = a.pop(1) returns 20.
TIP: Please refer to List article to understand everything about Python Lists and List functions.
# Python Pop List Items a = [10, 20, 30, 40] print("Original List Items are : ", a) a.pop(1) print("List Items are : ", a) a.pop(2) print("List Items are : ", a)
OUTPUT
Python List pop first, second
In this example, we declared a string list. Next, we used pop function to remove items at index position 1 and 2.
# Python Pop List Items Fruits = ['Apple', 'Orange', 'Banana', 'Kiwi', 'Grape'] print("Original List : ", Fruits) Fruits.pop(1) print("List Items are : ", Fruits) Fruits.pop(2) print("List Items are : ", Fruits)
OUTPUT
Python pop Example 3
Let me use this pop function on Mixed List. Here, we declared a mixed list of numbers and words. Next, we used the list pop function to remove items at index 1 and 2.
# Python Pop List Items MixList = ['apple', 1, 'Orange', 5, 'Kiwi', 'Mango'] print("Original List : ", MixList) MixList.pop(1) print("List Items are : ", MixList) MixList.pop(2) print("List Items are : ", MixList)
OUTPUT
Python Program to Remove List Items
This program removes or pops nested list items at the index position 2 and 3.
# Python Pop List Items Nested = [[71, 222], [22, 13], [11, 22], [44, 55], [99, 77]] print("Original List : ", Nested) Nested.pop(2) print("List Items are : ", Nested) Nested.pop(3) print("List Items are : ", Nested)
OUTPUT