List of pythons | pop ()

Python Methods and Functions

Syntax :

list_name.pop(index)

Parameter :

  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. 

list

Exception :

 When index is out of range, it returns IndexError 

Code # 1:

# Python3 program for the pop () method

 

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

  
# Jumps out and removes the last item from the list

print (list1.pop ())

 
# Print the list after removing the last item

print ( "New List after pop:" , list1, "" )

  

list2 = [ 1 , 2 , 3 , ( 'cat' , ' bat' ), 4 ]

  
# Pop the last three elements

print (list2.pop ())

print (list2.pop ())

print (list2.pop ())

 
# Print list

print ( "New List after pop:" , list2, "" )

Output:

 6 New List after pop: [1, 2, 3, 4, 5] 4 ('cat',' bat') 3 New List after pop: [1, 2] 

Code # 2:

< td class = "code">

# Python3 program showing the pop () method
# and the remaining list after each popup

 

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

 
# Jumps out and removes the last one
# item from the list

print (list1.pop (), list1)

  
# Pops up and removes 0th index
# item from list

print (list1.pop ( 0 ), list1)

Output:

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

Code # 3: IndexError

# 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 

Practical example:
The fruit list contains fruit_name and a property that speaks about its fruit. The other list contains two juices and is . With pop () and

# Python3 program demonstrating
# practical use of the pop () list

 

fruit = [[ 'Orange' , ' Fruit' ], [ 'Banana' , 'Fruit' ], [ ' Mango' , ' Fruit' ]]

consume = [ ' Juice' , 'Eat' ]

possible = []

 
# Loop through an item in the fruit list

for item in fruit:

 

# Heavy list use consume

for use in consume:

 

item.append (use)

result.append (item [:])

item.pop ( - 1 )

print (result)

Output:

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