The Wayback Machine - https://web.archive.org/web/20240926142722/https://www.geeksforgeeks.org/python-list-pop-method/
Open In App

Python List pop() Method

Last Updated : 09 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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
# Using list
fruits = ["apple","banana","cherry","carrot"]
# removing carrot from the list
fruits.pop()
# printing new list
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]
# Pops and removes the 3th index
# element from the list
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:

Python List pop() Method – FAQs

What Does pop() Do in Python?

In Python, the pop() method is used in different contexts with lists and dictionaries, performing slightly different functions:

  • For Lists: The pop() method removes and returns an element from the list at the specified position. If no index is specified, pop() removes and returns the last item in the list.
  • For Dictionaries: The pop() method removes the specified key and returns the corresponding value. If the key is not found, a default value can be returned if specified, otherwise a KeyError is raised.

Example:

my_list = [1, 2, 3, 4, 5]
popped_item = my_list.pop() # Removes the last item
print(popped_item) # Output: 5
print(my_list) # Output: [1, 2, 3, 4]

Example:

my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.pop('b')
print(value) # Output: 2
print(my_dict) # Output: {'a': 1, 'c': 3}

What is the Difference Between pop() and remove() Methods of List?

The difference between pop() and remove() methods in Python lists is how they delete items:

  • pop():
    • Removes and returns the element at the specified index.
    • If no index is provided, it removes and returns the last item of the list.
    • Can be useful when you need the value of the removed element.
  • remove():
    • Removes the first occurrence of a value without returning it.
    • Does not work by index but by the value itself.
    • If the value is not found, it raises a ValueError.

Example:

my_list = ['a', 'b', 'c', 'd']
my_list.pop(2) # 'c' is removed and returned

Example:

my_list = ['a', 'b', 'c', 'd']
my_list.remove('c') # 'c' is removed, nothing is returned

What is the Difference Between pop and index in Python List?

pop() and index() are fundamentally different methods used with lists:

  • pop():
    • Method for removing an item from the list by index and returns the item.
  • index():
    • Method for finding the index of the first occurrence of a specified value within the list.
    • Does not modify the list.
    • Raises a ValueError if the value is not found.

Example:

my_list = ['a', 'b', 'c', 'd']
index_of_c = my_list.index('c') # Returns 2
my_list.pop(index_of_c) # Removes 'c' from the list

What Function Does the pop() Method in a Dictionary Do?

In dictionaries, the pop() method is used to remove a specified key and return the corresponding value:

  • Removes the key-value pair from the dictionary.
  • If the key is not found and no default value is specified, it raises a KeyError. If a default value is provided, it returns this default value instead of raising an error.

Example:

my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.pop('b', 'Not Found') # Removes 'b' and returns 2
print(my_dict) # Output: {'a': 1, 'c': 3}
value_not_found = my_dict.pop('z', 'Not Found') # Returns 'Not Found' since 'z' is not in the dictionary
print(value_not_found)

These functionalities make pop() a versatile method for both lists and dictionaries in Python, allowing for controlled removal of elements by index or key, respectively



    Previous Article
    Next Article

    Similar Reads

    List Methods in Python | Set 2 (del, remove(), sort(), insert(), pop(), extend()...)
    Some of the list methods are mentioned in set 1 below List Methods in Python | Set 1 (in, not in, len(), min(), max()…) More methods are discussed in this article. 1. del[a : b] :- This method deletes all the elements in range starting from index 'a' till 'b' mentioned in arguments. 2. pop() :- This method deletes the element at the position mentio
    4 min read
    IndexError: pop from Empty List in Python
    The IndexError: pop from an empty list is a common issue in Python, occurring when an attempt is made to use the pop() method on a list that has no elements. This article explores the nature of this error, provides a clear example of its occurrence, and offers three practical solutions to handle it effectively. Here, we will see how to fix Pop From
    3 min read
    Python Set pop() Method
    Python set pop() removes any random element from the set and returns the removed element. In this article, we will see about the Python set pop() method. Example Input: {9, 1, 0} Output: {9, 1} Explanation: By using set pop() method, a random element 0 is removed from the set and remaining set is returned.Python Set pop() SyntaxSyntax: set_obj.pop(
    2 min read
    Python Dictionary pop() Method
    Python dictionary pop() method removes and returns the specified element from the dictionary. Example: C/C++ Code # inializing dictionary student student = {"rahul":7, "Aditya":1, "Shubham":4} # priting original dictionary print(student) # using dictionary pop suspended = student.pop("rahul") # checking key o
    4 min read
    Python | Pandas Dataframe.pop()
    Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas Pop() method is common in most of the data structures but pop() method is a little bit different from the rest. In a stack, pop do
    2 min read
    Python | Pandas Series.pop()
    Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.pop() function returns the item corresponding to the passed index label. It als
    2 min read
    Wand push() and pop() in Python
    We can use ImageMagick's internal graphic context stack to manage different styles and operations in Wand. There are total four push functions for context stack. push()push_clip_path()push_defs()push_pattern() push() function is used to grow context stack and pop() is another function and used to restore stack to previous push. Syntax : # for push(
    2 min read
    What Is Difference Between Del, Remove and Pop on Python Lists?
    In python del is a keyword and remove(), pop() are in-built methods. The purpose of these three are same but the behavior is different remove() method delete values or object from the list using value and del and pop() deletes values or object from the list using an index. del Keyword: The del keyword delete any variable, list of values from a list
    3 min read
    How to create a pop up message when a button is pressed in Python - Tkinter?
    In this article, we will see how to create a button and how to show a popup message when a button is pressed in Python. Tkinter is a standard Python Package for creating GUI applications. Tkinter may be a set of wrappers that implement the Tk widgets as Python classes. Python, when combined with Tkinter, provides a quick and straightforward way to
    2 min read
    IndexError: pop from Empty Deque in Python
    In Python, the IndexError: pop from an empty deque is an error that occurs when trying to use the pop() method on an empty deque. A deque (double-ended queue) is a versatile data structure that allows efficient addition and removal of elements from both ends. This article explores the causes of the error, provides examples of its occurrence, and of
    4 min read
    PyQt5 - Show pop up items of ComboBox when push button is pressed
    In this article we will see how we make combo box to show its elements without clicking on it. In order to do this we will use showPopup method. Syntax : combo_box.showPopup() Argument : It takes no argument Action performed : It will show the pop up elements Steps for implementation : 1. Create a combo box 2. Add items to the combo box 3. Create a
    2 min read
    PyQt5 - Closing pop up items of ComboBox when push button is pressed
    In this article we will see how we make combo box to hide its elements without clicking on it, in order to do this we will use hidePopup method. Syntax : combo_box.hidePopup() Argument : It takes no argument Action performed : It will hide the pop up elements Steps for implementation : 1. Create a combo box 2. Add items t the combo box 3. Create a
    2 min read
    PyQt5 QCalendarWidget - Enabling/Disabling Date Edit Pop-Up
    In this article, we will see how we enable/ disable the date edit pop-up of the QCalendarWidget. By default date edit pop-up is enabled, The date edit is simpler in appearance than QDateEdit, but allows the user to navigate between fields using the left and right cursor keys, increment and decrement individual fields using the up and down cursor ke
    2 min read
    PyQt5 QCalendarWidget - Checking if Date Edit Pop-Up is enabled or disabled
    In this article we will see how we check the date edit pop-up of the QCalendarWidget is enabled or not. By default date edit pop-up is enabled, The date edit is simpler in appearance than QDateEdit, but allows the user to navigate between fields using the left and right cursor keys, increment and decrement individual fields using the up and down cu
    2 min read
    PyQt5 QCalendarWidget - Setting Date Edit (Pop-Up) Accept Delay Property
    In this article, we will see how we can set/change the date edit accept delay property of the QCalendarWidget. This property holds the time an inactive date edit is shown before its contents are accepted. If the calendar widget's date edit is enabled, this property specifies the amount of time (in milliseconds) that the date edit remains open after
    2 min read
    PyQt5 QCalendarWidget - Getting Date Edit (Pop-Up) Accept Delay
    In this article, we will see how we can get the date edit accept delay property of the QCalendarWidget. This property holds the time an inactive date edit is shown before its contents are accepted. If the calendar widget's date edit is enabled, this property specifies the amount of time (in milliseconds) that the date edit remains open after the mo
    2 min read
    How to Create a pop up in pygame with pgu?
    In this article, we will learn about how to create a pop-up in pygame with pgu in Python. PyGame The pygame library is an open-source Python module designed to assist you in creating games and other multimedia applications. Pygame, which is built on top of the highly portable SDL (Simple DirectMedia Layer) development library, can run on a variety
    6 min read
    Python | Convert list of string to list of list
    Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to la ist to perform tasks is quite common in web development. Let's discuss certain ways in which this
    7 min read
    Class Method vs Static Method vs Instance Method in Python
    Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
    5 min read
    Python | Maximum sum of elements of list in a list of lists
    Given lists in a list, find the maximum sum of elements of list in a list of lists. Examples: Input : [[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]] Output : 33 Explanation: sum of all lists in the given list of lists are: list1 = 6, list2 = 15, list3 = 33, list4 = 24 so the maximum among these is of Input : [[3, 4, 5], [1, 2, 3], [0, 9, 0]] Outpu
    4 min read
    Python List Comprehension | Segregate 0's and 1's in an array list
    You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array. Examples: Input : arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] Output : [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] We have existing solution for this problem please refer Segregate 0s and 1s in an array link. We can solve this problem quickly in Python usi
    2 min read
    Python | Sort list of list by specified index
    We can sort the list of lists by using the conventional sort function. This sort the list by the specified index of lists. Let's discuss certain ways in which this task can be performed using Python. Method 1: Using the bubble sort algorithm Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each
    8 min read
    Python | Remove all values from a list present in other list
    Sometimes we need to perform the operation of removing all the items from the lists that are present in another list, i.e we are given some of the invalid numbers in one list which need to be get ridden from the original list. Let's discuss various ways How to remove the elements of a list from another list in Python. Illustration: Input: List one
    10 min read
    Python | Sort list according to other list order
    Sorting is an essential utility used in majority of programming, be it for competitive programming or development. Conventional sorting has been dealt earlier many times. This particular article deals with sorting with respect to some other list elements. Let's discuss certain ways to sort list according to other list order. Method #1 : Using List
    5 min read
    Python | Ways to Convert a 3D list into a 2D list
    List is a common type of data structure in Python. While we have used the list and 2d list, the use of 3d list is increasing day by day, mostly in case of web development. Given a 3D list, the task is to convert it into a 2D list. These type of problems are encountered while working on projects or while contributing to open source. Below are some w
    3 min read
    Python | Merge List with common elements in a List of Lists
    Given a list of list, we have to merge all sub-list having common elements. These type of problems are very frequent in College examinations and while solving coding competitions. Below are some ways to achieve this. Input: [[11, 27, 13], [11, 27, 55], [22, 0, 43], [22, 0, 96], [13, 27, 11], [13, 27, 55], [43, 0, 22], [43, 0, 96], [55, 27, 11]] Out
    3 min read
    Python | Subtract two list elements if element in first list is greater
    Given two list, If element in first list in greater than element in second list, then subtract it, else return the element of first list only.Examples: Input: l1 = [10, 20, 30, 40, 50, 60] l2 = [60, 50, 40, 30, 20, 10] Output: [10, 20, 30, 10, 30, 50] Input: l1 = [15, 9, 10, 56, 23, 78, 5, 4, 9] l2 = [9, 4, 5, 36, 47, 26, 10, 45, 87] Output: [6, 5,
    5 min read
    Python - Filter the List of String whose index in second List contains the given Substring
    Given two lists, extract all elements from the first list, whose corresponding index in the second list contains the required substring. Examples: Input : test_list1 = ["Gfg", "is", "not", "best", "and", "not", "CS"], test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "thats ok"], sub_str = "ok" Output : ['Gfg', 'is', 'best', 'an
    10 min read
    Appending Item to Lists of list using List Comprehension | Python
    If you are a Python user, you would know that in Python, we can use the append() method to add an item to an existing list. This list may already contain other items or be empty. Further, the item to be added can simply be a number a character, or even an entire tuple or list. However, if you are trying to append an item to lists within a list comp
    5 min read
    cmp(list) method in Python
    cmp(list) is a method specified in Number in Python 2. The comparison of integral numbers have been discussed using cmp(). But many a times, there is a need to compare the entire list that can be composed of similar or different data types. In this case, different case scenarios occur and having knowledge of them can at times prove to be quite hand
    4 min read