Python List pop() Method
Last Updated :
21 Dec, 2023
Python list pop() function removes elements at a specific index from the list.
Example
Python
fruits = [ "apple" , "mango" , "cherry" ]
fruits.pop()
print (fruits)
|
Output:
['apple', 'mango']
Python List pop() Syntax
list_name.pop(index)
Parameter
- index (optional) – The value at the 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:pop() method raises IndexError when the index is out of range.
What is the List pop method()?
pop() function removes and returns the value at a specific index from a list. It is an inbuilt function of Python.
It can be used with and without parameters; without a parameter list pop() returns and removes the last value from the list by default, but when given an index value as a parameter, it only returns and removes the element at that index.
How to Use List pop() Method in Python?
You can easily use pop() function in Python. Using the list pop() method you can remove an element from the list. Let’s understand it with an example:
Python
fruits = [ "apple" , "banana" , "cherry" , "carrot" ]
fruits.pop()
print (fruits)
|
Output
['apple', 'banana', 'cherry']
More List pop() Examples
Let’s see how to pop an item from a list with examples:
1. Pop last element from list
Following code Pops and removes the last element from the list in Python.
Python
my_list = [ 1 , 2 , 3 , 4 ]
print ( "Popped element:" , my_list.pop())
print ( "List after pop():" , my_list)
|
Output
Popped element: 4
List after pop(): [1, 2, 3]
2. Pop the Item at a Specific Index from the List
Pops and removes the 3rd index element from the list.
Python
my_list = [ 1 , 2 , 3 , 4 , 5 , 6 ]
print (my_list.pop( 3 ), my_list)
|
Output
4 [1, 2, 3, 5, 6]
3. Pop element at a Negative Index from a List
Pops and removes element 5 from the list.
Python
my_list = [ 1 , 2 , 3 , 4 , 5 , 6 ]
poped_item = my_list.pop( - 2 )
print ( "New list" , my_list)
print ( "Poped Item" , poped_item)
|
Output
New list [1, 2, 3, 4, 6]
Poped Item 5
Note: List pop() time complexity = O(n)
In this article, we have covered the Python list pop() function which is used to remove elements from a list. The list pop() method is an important operation of a list.
Read More Python List Methods
Also Read:
Please Login to comment...