Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python List pop()

#1
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:


Argument Description
index Optional 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 respective 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


Python List pop() First n Elements


Python List pop() Last n Elements


Python List pop() Time Complexity … First and Last and General cases


Python List pop() vs remove()


Python List Pop and Push (Stack)


Python List pop() Without Remove


Python List pop() While Iterating


Python List pop() If Not Empty


Python List pop() Slice


Alternatives Ways to Remove Elements From a List


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


Method Description
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 comprehension Remove 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.



https://www.sickgaming.net/blog/2020/03/...-list-pop/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] How to Install PIL/Pillow in Python? A Helpful Illustrated Guide xSicKxBot 0 5 10-27-2020, 12:00 AM
Last Post: xSicKxBot
  [Tut] How to Read a File Line-By-Line and Store Into a List? xSicKxBot 0 6 10-24-2020, 06:12 PM
Last Post: xSicKxBot
  [Tut] How To Kill A Thread In Python? xSicKxBot 0 8 10-24-2020, 05:40 AM
Last Post: xSicKxBot
  [Tut] Python’s NameError: name ‘xxx’ is not defined — How to Fix This Stupid Bug? xSicKxBot 0 18 10-16-2020, 10:30 PM
Last Post: xSicKxBot
  [Tut] Python IndentationError: unexpected indent (How to Fix This Stupid Bug) xSicKxBot 0 21 10-10-2020, 08:24 PM
Last Post: xSicKxBot
  [Tut] Yield Keyword in Python – A Simple Illustrated Guide xSicKxBot 0 22 10-09-2020, 06:13 PM
Last Post: xSicKxBot
  [Tut] Python Reverse List with Slicing — An Illustrated Guide xSicKxBot 0 40 10-02-2020, 04:24 AM
Last Post: xSicKxBot
  [Tut] How to Remove Duplicates From a Python List While Preserving Order? xSicKxBot 0 38 10-01-2020, 02:21 AM
Last Post: xSicKxBot
  [Tut] How To Update A Key In A Dictionary In Python If The Key Doesn’t Exist? xSicKxBot 0 43 09-29-2020, 09:02 PM
Last Post: xSicKxBot
  [Tut] How to Get the Last Element of a Python List? xSicKxBot 0 43 09-28-2020, 02:36 AM
Last Post: xSicKxBot

Forum Jump:

Become a Patron!
[-]
Upcoming Events

[-]
Latest Threads
ODIN 2 Synthesizer VST
Last Post: xSicKxBot
Yesterday 11:24 PM
» Replies: 0
» Views: 2
Microsoft - Cyberattacks target internat...
Last Post: xSicKxBot
Yesterday 11:24 PM
» Replies: 0
» Views: 1
Fedora - What’s new in Fedora 33 Worksta...
Last Post: xSicKxBot
Yesterday 11:24 PM
» Replies: 0
» Views: 1
News - No More Heroes 1 & 2 Are Both Ava...
Last Post: xSicKxBot
Yesterday 11:24 PM
» Replies: 0
» Views: 1
News - Bravely Default 2 Preorders Are L...
Last Post: xSicKxBot
Yesterday 11:24 PM
» Replies: 0
» Views: 2
(Indie Deal) Tropico 6, Assassin's Creed...
Last Post: xSicKxBot
Yesterday 04:41 PM
» Replies: 0
» Views: 4
gRPC performance improvements in .NET 5
Last Post: xSicKxBot
Yesterday 04:40 PM
» Replies: 0
» Views: 2
News - Season of the Hunt
Last Post: xSicKxBot
Yesterday 04:40 PM
» Replies: 0
» Views: 2
News - Rumour: Hyrule Warriors: Age Of C...
Last Post: xSicKxBot
Yesterday 04:39 PM
» Replies: 0
» Views: 2
News - It’s Been Three Years Since We Fi...
Last Post: xSicKxBot
Yesterday 04:39 PM
» Replies: 0
» Views: 2

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2020