![]() |
|
[Tut] Python List pop() - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python List pop() (/thread-94133.html) |
[Tut] Python List pop() - xSicKxBot - 03-20-2020 Python List pop() This tutorial shows you everything you need to know to help you master the essential Code: pop()Definition and Usage: The Code: list.pop()Code: listCode: list.pop(index)Code: indexCode: indexHere’s a short example: Code: >>> lst = [1, 2, 3]
>>> lst.pop()
3
>>> lst
[1, 2]In the first line of the example, you create the list Code: lstCode: [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? https://repl.it/repls/UsedSquareExperiments?lite=true 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: Code: list.pop(index=-1)Arguments: Argument | Description Code: 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 Code: list.pop()Code: ObjectVideo: Python List pop() By Index You can use the Code: list.pop(index)Code: indexHere’s an example: Code: >>> 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 Code: 'Ann'Code: 'Alice'Python List pop() First / Front / Left / Head The Code: list.pop(index)Code: indexCode: index=0Code: list.pop(0)Here’s an example: Code: >>> primes = [1, 2, 3, 5, 7, 11]
>>> primes.pop(0)
1
>>> primes
[2, 3, 5, 7, 11]The Code: pop(0)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 Code: list.index(value)Code: list.pop(index)Here’s an example where you want to pop the element 7 from the list and store the result in the variable Code: some_primeCode: >>> primes = [1, 2, 3, 5, 7, 11]
>>> some_prime = primes.pop(primes.index(7))
>>> some_prime
7If you’re not interested in the return value but you only want to remove the first occurrence of the value Code: xCode: listCode: list.remove(x)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 Code: lst.remove(x)Remove an element from the list (by value) Code: lst.pop()Remove an element from the list (by index) and return the element Code: lst.clear()Remove all elements from the list Code: 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 Code: list.remove(element)Code: >>> lst = ["Alice", 3, "alice", "Ann", 42]
>>> lst.remove("Ann")
>>> lst
['Alice', 3, 'alice', 42]Try it yourself: https://repl.it/repls/CurlyIdioticChief?lite=true 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: Code: >>> 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 listhttps://repl.it/repls/CurlyIdioticChief?lite=true Per default, the Code: pop()Code: >>> 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! Code: >>> lst = ['Alice', 'Bob', 'Ann']
>>> lst.pop(1) 'Bob'
>>> lst
['Alice', 'Ann']https://repl.it/repls/TightWiseTechnician?lite=true The Code: clear()Code: >>> lst = ['Alice', 'Bob', 'Ann']
>>> lst.clear()
>>> lst
[]https://repl.it/repls/ClientsideForsakenFrontpage?lite=true This trick is also relatively unknown among Python beginners:
Code: >>> 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 https://repl.it/repls/FabulousMadEquation?lite=true 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 ].
The example Code: [x for x in range(3)]Code: [0, 1, 2]You can also define a condition such as all odd values Code: x%2==1Code: >>> 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 Code: lstCode: x%2Related 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 Code: pop()In other words: can you call the Code: pop()The answer is yes (if you use the cPythonimplementation). 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 Code: list.remove(element)Code: elementCode: listYou’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. |