Python List pop()

This tutorial shows you everything you need to know to help you master the essential pop() method of the most fundamental container data type in the Python programming language.

Definition and Usage:

The list.pop() method removes and returns the last element from an existing list. The list.pop(index) method with the optional argument index removes and returns the element at the position index.

Here’s a short example:

>>> lst = [1, 2, 3]
>>> lst.pop()
3
>>> lst
[1, 2]

In the first line of the example, you create the list lst. You then remove and return the final element 3 from the list. The result is the list with only two elements [1, 2].

Code Puzzle — Try It Yourself:

Now you know the basics. Let’s deepen your understanding with a short code puzzle—can you solve it?

You can also solve this puzzle and track your Python skills on our interactive Finxter app.

Syntax:

You can call this method on each list object in Python. Here’s the syntax:

list.pop(index=-1)

Arguments:

ArgumentDescription
indexOptional argument. You can define the index of the element to be removed and returned. The default argument leads to the removal of the last list element with index -1.

Return value:

The method list.pop() has return value Object. It removes the particular element from the list (default: the last element) and returns it directly to the caller.

Video:

Python List pop() By Index

You can use the list.pop(index) method to with the optional index argument to remove and return the element at position index from the list.

Here’s an example:

>>> customers = ['Alice', 'Bob', 'Ann', 'Frank']
>>> customers.pop(2)
'Ann'
>>> customers
['Alice', 'Bob', 'Frank']
>>> customers.pop(0)
'Alice'
>>> customers
['Bob', 'Frank']

After creating the list with four elements, you first remove and return the second element 'Ann'. Then, you remove and return the first element 'Alice'. The resulting list has only two elements left.

Python List pop() First / Front / Left / Head

The list.pop(index) method to with the optional index argument to remove and return the element at position index from the list. So if you want to remove the first element from the list, simply set index=0 by calling list.pop(0). This will pop the first element from the list.

Here’s an example:

>>> primes = [1, 2, 3, 5, 7, 11]
>>> primes.pop(0)
1
>>> primes
[2, 3, 5, 7, 11]

The pop(0) method removes the first element 1 from the list of prime numbers given in the example.

Python List pop() By Value

In the previous two examples, you’ve seen how to pop elements by index. But can you also pop by value?

Yes, you can by using the list.index(value) method which gives you the index of the element value in the list. Now, you can use the list.pop(index) method on this index to remove the value from the list and get the result as a return value.

Here’s an example where you want to pop the element 7 from the list and store the result in the variable some_prime.

>>> primes = [1, 2, 3, 5, 7, 11]
>>> some_prime = primes.pop(primes.index(7))
>>> some_prime
7

If you’re not interested in the return value but you only want to remove the first occurrence of the value x in the list, use the list.remove(x) method.

Related Article:

Python List pop() Multiple Elements

If you can pop one element from a Python list, the natural question is if you can also pop multiple elements at the same time?

The answer no. You cannot directly pop multiple element from a list. But you can do it indirectly with a simple list comprehension statement.

Python List pop() First n Elements

Say, you want to pop the first n elements from a list. How do you do this?

You simply create a list of values using list comprehension [list.pop(0) for i in range(n)] to remove and return the first n elements of the list.

Here’s another example:

>>> lst = ['a', 'b', 'c', 'd', 'e', 'f']
>>> popped = [lst.pop(0) for i in range(5)]
>>> popped
['a', 'b', 'c', 'd', 'e']
>>> lst
['f']

The popped list contains the first five elements. The original list has only one element left.

Python List pop() Last n Elements

Say, you want to pop the last n elements from a list. How do you do this?

You simply create a list of values using list comprehension [list.pop() for i in range(n)] to remove and return the last n elements of the list.

Here’s another example:

>>> lst = ['a', 'b', 'c', 'd', 'e', 'f']
>>> [lst.pop() for i in range(5)]
['f', 'e', 'd', 'c', 'b']
>>> lst
['a']

The popped list contains the last five elements. The original list has only one element left.

Python List pop() Time Complexity

The time complexity of the pop() method is constant O(1). No matter how many elements are in the list, popping an element from a list takes the same time (plus minus constant factors).

The reason is that lists are implemented with arrays in cPython. Retrieving an element from an array has constant complexity. Removing the element from the array also has constant complexity. Thus, retrieving and removing the element as done by the pop() method has constant runtime complexity too.

I’ve written a short script to evaluate runtime complexity of the pop() method in Python:

import matplotlib.pyplot as plt
import time

y = []
for i in [100000 * j for j in range(5,15)]:
    lst = list(range(i))
    t0 = time.time()
    x = lst.pop(0)
    t1 = time.time()
    y.append(t1-t0)


plt.plot(y)
plt.xlabel("List elements (10**5)")
plt.ylabel("Time (sec)")
plt.show()

The resulting plot shows that the runtime complexity is linear, even if the number of elements increases drastically:

Runtime Complexity Python pop()

(Okay, there are some bumps but who really cares?)

Note that the runtime complexity is still linear if we pop the last element or any other arbitrary element from the list.

Python List pop() vs remove()

What’s the difference between the list.pop() and the list.remove() methods?

  • The list.remove(element) method removes the first occurrence of the element from an existing list. It does not, however, remove all occurrences of the element in the list!
  • The list.pop() method removes and returns the last element from an existing list. The list.pop(index) method with the optional argument index removes and returns the element at the position index.

So, the remove method removes by value and the pop method removes by index. Also, the remove method returns nothing (it operates on the list itself) and the pop method returns the removed object.

Python List Pop and Push (Stack)

Python doesn’t have a built-in stack data structure because it’s not needed. You can simply create an empty list and call it stack. Then, you use the stack.append(x) method to push element x to the stack. And you sue the stack.pop() method to push the topmost element from the stack.

Here’s an example that shows how to push three values to the stack and then removing them in the traditional First-In Last-Out (FILO) order of stacks.

>>> stack = []
>>> stack.append(5)
>>> stack.append(42)
>>> stack.append("Ann")
>>> stack.pop()
'Ann'
>>> stack.pop()
42
>>> stack.pop()
5
>>> stack
[]

Python List pop() Without Remove

Want to pop() an element from a given list without removing it? Don’t do it! Instead, use simple indexing. To get an element with index i from list, simply use indexing scheme list[i]. This will keep the original element in the list without removing it.

Python List pop() If Not Empty

How can you pop() an element only if the list is not empty in a single line of code? Use the ternary operator in Python lst.pop() if lst else None as follows:

>>> lst = [1, 2, 3]
>>> for i in range(5):
	print(lst.pop() if lst else None)

	
3
2
1
None
None

You try to pop the leftmost element five times from a list with only three values. However, there’s no error message because of your proficient use of the ternary operator that checks in a single line if the list is empty. If it is empty, it doesn’t pop but return the None value.

If you don’t use the ternary operator in this example, Python will throw an IndexError as you try to pop from an empty list:

>>> lst = [1, 2, 3]
>>> for i in range(5):
	print(lst.pop())

	
3
2
1
Traceback (most recent call last):
  File "<pyshell#15>", line 2, in <module>
    print(lst.pop())
IndexError: pop from empty list

Python List pop() Slice

Can you pop a whole slice at once? Well, you can remove a whole slice by using the del keyword: to remove slice lst[start:stop] from the list, you can call del lst[start:stop]. However, you won’t get the slice as a return value so you may want to store the slice in a separate variable first, before removing it from the list.

Python List pop() While Iterating

It’s always dangerous to change a list over which you currently iterate.

Why? Because the iterator is created only once in the loop definition and it will stubbornly give you the indices it prepared in the beginning. If the loop changes, the indices of the elements change, too. But the iterator doesn’t adapt the indices to account for those changes. Here’s an example:

>>> lst = list(range(10))
>>> for i in range(len(lst)):
	lst.pop(i)

	
0
2
4
6
8
Traceback (most recent call last):
  File "<pyshell#20>", line 2, in <module>
    lst.pop(i)
IndexError: pop index out of range

Wow—this was unexpected, wasn’t it? You popped only every second element from the list. Why? Because in the first iteration, the index variable i=0. Now, we remove this from the list. The element 1 in the list has now index 0 after removal of the previous leading element. But in the second loop iteration, the loop variable has index i=1. This is the next element to be popped. But you have skipped popping the element 1 from the list at position index 0! Only every other element is popped as a result.

Alternatives Ways to Remove Elements From a List

There are some alternative ways to remove elements from the list. See the overview table:

MethodDescription
lst.remove(x)Remove an element from the list (by value)
lst.pop()Remove an element from the list (by index) and return the element
lst.clear()Remove all elements from the list
del lst[3]Remove one or more elements from the list (by index or slice)
List comprehensionRemove all elements that meet a certain condition

Next, you’ll dive into each of those methods to gain some deep understanding.

remove() — Remove An Element by Value

To remove an element from the list, use the list.remove(element) method you’ve already seen previously:

>>> lst = ["Alice", 3, "alice", "Ann", 42]
>>> lst.remove("Ann")
>>> lst
['Alice', 3, 'alice', 42]

Try it yourself:

The method goes from left to right and removes the first occurrence of the element that’s equal to the one to be removed.

Removed Element Does Not Exist

If you’re trying to remove element x from the list but x does not exist in the list, Python throws a Value error:

>>> lst = ['Alice', 'Bob', 'Ann']
>>> lst.remove('Frank')
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    lst.remove('Frank')
ValueError: list.remove(x): x not in list

pop() — Remove An Element by Index

Per default, the pop() method removes the last element from the list and returns the element.

>>> lst = ['Alice', 'Bob', 'Ann']
>>> lst.pop()
'Ann'
>>> lst
['Alice', 'Bob']

But you can also define the optional index argument. In this case, you’ll remove the element at the given index—a little known Python secret!

>>> lst = ['Alice', 'Bob', 'Ann']
>>> lst.pop(1)
'Bob'
>>> lst
['Alice', 'Ann']

clear() — Remove All Elements

The clear() method simply removes all elements from a given list object.

>>> lst = ['Alice', 'Bob', 'Ann']
>>> lst.clear()
>>> lst
[]

del — Remove Elements by Index or Slice

This trick is also relatively unknown among Python beginners:

  • Use del lst[index] to remove the element at index.
  • Use del lst[start:stop] to remove all elements in the slice.
>>> lst = list(range(10))
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del lst[5]
>>> lst
[0, 1, 2, 3, 4, 6, 7, 8, 9]
>>> del lst[:4]
>>> lst
[4, 6, 7, 8, 9]

Related blog articles:

List Comprehension — Remove Elements Conditionally

Okay, this is kind of cheating because this method does not really remove elements from a list object. It merely creates a new list with some elements that meet your condition.

List comprehension is a compact way of creating lists. The simple formula is [ expression + context ].

  • Expression: What to do with each list element?
  • Context: What list elements to select? It consists of an arbitrary number of for and if statements.

The example [x for x in range(3)] creates the list [0, 1, 2].

You can also define a condition such as all odd values x%2==1 in the context part by using an if condition. This leads us to a way to remove all elements that do not meet a certain condition in a given list.

>>> lst = list(range(10))
>>> lst_new = [x for x in lst if x%2]
>>> lst_new
[1, 3, 5, 7, 9] 

While you iterate over the whole list lst, the condition x%2 requires that the elements are odd.

Related blog articles:

Python List pop() Thread Safe

Do you have a multiple threads that access your list at the same time? Then you need to be sure that the list operations (such as pop()) are actually thread safe.

In other words: can you call the pop() operation in two threads on the same list at the same time? (And can you be sure that the result is meaningful?)

The answer is yes (if you use the cPython implementation). The reason is Python’s global interpreter lock that ensures that a thread that’s currently working on it’s code will first finish its current basic Python operation as defined by the cPython implementation. Only if it terminates with this operation will the next thread be able to access the computational resource. This is ensured with a sophisticated locking scheme by the cPython implementation.

The only thing you need to know is that each basic operation in the cPython implementation is atomic. It’s executed wholly and at once before any other thread has the chance to run on the same virtual engine. Therefore, there are no race conditions. An example for such a race condition would be the following: the first thread reads a value from the list, the second threads overwrites the value, and the first thread overwrites the value again invalidating the second thread’s operation.

All cPython operations are thread-safe. But if you combine those operations into higher-level functions, those are not generally thread safe as they consist of many (possibly interleaving) operations.

Where to Go From Here?

The list.remove(element) method removes the first occurrence of element from the list.

You’ve learned the ins and outs of this important Python list method.

If you keep struggling with those basic Python commands and you feel stuck in your learning progress, I’ve got something for you: Python One-Liners (Amazon Link).

In the book, I’ll give you a thorough overview of critical computer science topics such as machine learning, regular expression, data science, NumPy, and Python basics—all in a single line of Python code!

Get the book from Amazon!

OFFICIAL BOOK DESCRIPTION: Python One-Liners will show readers how to perform useful tasks with one line of Python code. Following a brief Python refresher, the book covers essential advanced topics like slicing, list comprehension, broadcasting, lambda functions, algorithms, regular expressions, neural networks, logistic regression and more. Each of the 50 book sections introduces a problem to solve, walks the reader through the skills necessary to solve that problem, then provides a concise one-liner Python solution with a detailed explanation.