Click for All Topics
.pop()
method is used to pop an element from a list by index position..pop()
method returns a popped element that you can use further in your code..pop()
method on an empty list and when you pass the index outside the list range.
Syntax –
list.pop(index)
Parameter –
Example 1- Remove the last element from the list
my_list=[2,4,6,8,10]
print("Original list:",my_list)
my_list.pop()
print("Modified original list:",my_list)
# Output -
# Original list: [2, 4, 6, 8, 10]
# Modified original list: [2, 4, 6, 8]
.pop()
method.
Example 2- pop an element from a list by a specific index position
my_list=['hello', 'python', 'method', 'pop']
print("Original list:",my_list)
my_list.pop(2)
print("Modified Original list:",my_list)
# Output -
# Original list: ['hello', 'python', 'method', 'pop']
# Modified Original list: ['hello', 'python', 'pop']
Example 3- pop an element from a list by using negative indexing
It_city=['Bangalore','Noida', 'Pune', 'Gwalior', 'Hyderabad']
print("Original list:",It_city)
It_city.pop(-2)
print("Modified Original list:",It_city)
# Output -
# Original list: ['Bangalore', 'Noida', 'Pune', 'Gwalior', 'Hyderabad']
# Modified Original list: ['Bangalore', 'Noida', 'Pune', 'Hyderabad']
Example 4- sorting a list using the.pop()
method
l=[11,14,2,15,9,5,7]
print("Original unsorted list:",l)
l1=[]
for i in range(len(l)):
index=l.index(min(l))
popped_element=l.pop(index)
l1.append(popped_element)
print("Sorted original list:",l1)
# Output -
# Original unsorted list: [11,14,2,15,9,5,7]
# Sorted original list: [2, 5, 7, 9, 11, 14, 15]
Example 5- Let’s try to remove an element by giving an index out of range
subject=['Data Mining', 'Software Architecture', 'Big Data']
print("Original Subject list:",subject)
subject.pop(3) # will throw an error because index range(0,2)
print("Modified subject list:",subject)
# Output -
# Original Subject list: ['Data Mining', 'Software Architecture', 'Big Data']
# Traceback (most recent call last):
# File "/home/main.py", line 3, in
# subject.pop(3)
# IndexError: pop index out of range
remove() | pop() |
---|---|
It removes the element from a list by value | It is used to remove the element by the index of the element |
This method doesn’t return anything | This method returns the popped element |
When you do not pass any value to this method it will give an error ValueError . | When you do not pass any value then it will remove the last element by default |
It will give an error when the passed element doesn’t exist in the list | It will give an error when the passed index is out of range. |
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India