The Wayback Machine - http://web.archive.org/web/20220930142322/https://www.geeksforgeeks.org/python-list-pop-method/
Skip to content
Related Articles

Related Articles

Python List pop() Method

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 25 Aug, 2022
View Discussion
Improve Article
Save Article

Python list pop() is an inbuilt function in Python that removes and returns the last value from the List or the given index value.

Python List pop() Method Syntax

Syntax: list_name.pop(index)

  • index (optional) – The value at index is popped out and removed. If the index is not given, then the last element is popped out and removed.

Return: Returns The last value or the given index value from the list.

Exception: Raises IndexError When the index is out of range.

Python List pop() Method Example

Python3




l = [1, 2, 3, 4]
print("Popped element:", l.pop())
print("List after pop():", l)

Output:

Popped element: 4
List after pop(): [1, 2, 3]

Example 1: Using List pop() method to pop an element at the given index

Python3




list1 = [1, 2, 3, 4, 5, 6]
  
# Pops and removes the last 
# element from the list
print(list1.pop(), list1)
  
# Pops and removes the 0th index
# element from the list
print(list1.pop(0), list1)

Output:

6 [1, 2, 3, 4, 5]
1 [2, 3, 4, 5]

Example 2: Demonstrating IndexError 

Python3




# Python3 program for error in pop() method
  
list1 = [ 1, 2, 3, 4, 5, 6 ]
print(list1.pop(8))

Output: 

Traceback (most recent call last):
  File "/home/1875538d94d5aecde6edea47b57a2212.py", line 5, in 
    print(list1.pop(8))
IndexError: pop index out of range

Example 3: Practical Example

A list of the fruit contains fruit_name and property saying its fruit. Another list consume has two items juice and eat. With the help of pop() and append() we can do something interesting. 

Python3




fruit = [['Orange','Fruit'],['Banana','Fruit'], ['Mango', 'Fruit']]
consume = ['Juice', 'Eat']
possible = []
  
# Iterating item in list fruit
for item in fruit :
    # Iterating use in list consume
    for use in consume :
        item.append(use)
        possible.append(item[:])
        item.pop(-1)
print(possible)

Output: 

[['Orange', 'Fruit', 'Juice'], ['Orange', 'Fruit', 'Eat'],
 ['Banana', 'Fruit', 'Juice'], ['Banana', 'Fruit', 'Eat'],
 ['Mango', 'Fruit', 'Juice'], ['Mango', 'Fruit', 'Eat']]

Time Complexity : 

The complexity of all the above examples is constant O(1) in both average and amortized case 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!