![]() |
|
[Tut] Python List count() - 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 count() (/thread-94210.html) |
[Tut] Python List count() - xSicKxBot - 03-24-2020 Python List count() This tutorial shows you everything you need to know to help you master the essential Code: count()Definition and Usage: The Code: list.count(x)Code: xCode: listHere’s a short example: Code: >>> lst = [1, 2, 42, 2, 1, 42, 42]
>>> lst.count(42)
3
>>> lst.count(2)
2In the first line of the example, you create the list Code: lstCode 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/@finxter/ListCount?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.count(value)Arguments: Argument | Description Code: valueCounts the number of occurrences of Code: valueCode: listCode: ==Code: TrueReturn value: The method Code: list.count(value)Code: valuePython List Count Values Python List Count Duplicates Python List Count Unique Values and Strings Python List Count All Elements Python List Count Lambda Python List Count With Condition Python List Count If Python List Count Greater Than Python List Count Smaller Than Python List Count Regex Python List Count Matches Python List Count Wildcard Python List Count Not Working Python List Count Runtime Complexity Python List Reference Count Python List Count to Dict Python List Count Tuples Python List Count Zero / Non-Zero Python List Count and Sort Python List Count Slow Python List Count Group By Python List Count vs Len Python List reverse() Time Complexity The time complexity of the Code: reverse()You can see a plot of the time complexity of the Code: reverse()![]() The figure shows how the elapsed time of reversing lists with growing number of elements grows linear to the number of elements. If you’re interested in the code I used to generate this plot with Matplotlib, this is it: Code: import matplotlib.pyplot as plt
import time y = []
for i in [100000 * j for j in range(10,100)]: lst = list(range(i)) t0 = time.time() x = lst.reverse() t1 = time.time() y.append(t1-t0) plt.plot(y)
plt.xlabel("List elements (10**5)")
plt.ylabel("Time (sec)")
plt.show()If you call the Code: list.reverse()This is a common mistake of many Python beginners. They assume that the Code: reverse()Code: reverse()You can see this in the following example: Code: >>> lst = [1, 2, 3]
>>> lst.reverse()
>>> lst
[3, 2, 1]In the example, you only reversed the existing list Code: lstPython List reverse() None The return value of the Code: list.reverse()Code: NoneYou’ve seen an example of this in the previous section. Python List Reverse List Without reverse() You can also reverse a list without using the reverse() method. Let’s have a look at the following table that shows all reverse() alternatives: Method | Description Code: lst.reverse()Reverses the order of the elements of list Code: lstCode: list(reversed(lst))The built-in Code: reversed(lst)Code: lst[::-1]Slicing with negative indexing is the most concise way of reversing the order of a list. It creates a new list object. Code: [lst[i] for i in range(len(lst)-1,-1,-1)]Just for fun—one-liner solution to reverse a list using list comprehension and the negative range function. There is a fifth solution using recursion. But it’s highly inefficient and you shouldn’t use it in practice. If you want to learn about it anyways, read on. But don’t tell me you haven’t been warned! Python List Reverse Recursive You can create a recursive function to reverse any list. I’ll give you the code first and explain it later: Code: >>> reverse = lambda lst: reverse(lst[1:]) + [lst[0]] if lst else []Let’s check if it does what it’s supposed to do (reversing the list): Code: >>> reverse([1, 2, 3])
[3, 2, 1]
>>> reverse(["Ann", 1, 42, 0])
[0, 42, 1, 'Ann']
>>> reverse([])
[]
>>> reverse([1])
[1]Okay, it works! The recursive one-liner solution uses several Python features you have to understand before you can understand it entirely:
Phew! Quite some information to digest! But that’s not all. If you’ve understood all of the above, you also need to understand recursion. That’s too much to teach in a single paragraph so I’d send you over to my blog article about recursion. I’ll say only that much: to understand recursion, you first need to understand recursion! ![]() Python List Reverse Slice Slicingis the easiest way to reverse a list. To reverse the list Code: lstCode: lst[::-1]Code: startCode: stopCode: -1There’s only one case where you shouldn’t use slicing to reverse the list and this is if you don’t want to create a new list. In this case, stick to the Code: lst.reverse()Here’s an example of slicing to reverse a given list: Code: >>> friends = ["Ann", "Carsten", "Bob", "Alice"]
>>> r_friends = friends[::-1]
>>> friends
['Ann', 'Carsten', 'Bob', 'Alice']
>>> r_friends
['Alice', 'Bob', 'Carsten', 'Ann']You see that the two lists Code: friendsCode: r_friendsRelated articles: Python List Reverse Copy There are two ways to copy a list and reverse the order of its elements:
Here are both in action: Code: >>> lst_1 = ['Alice', 'Bob', 'Ann']
>>> lst_2 = lst_1[::-1]
>>> lst_3 = list(reversed(lst_1))
>>> lst_1
['Alice', 'Bob', 'Ann']
>>> lst_2
['Ann', 'Bob', 'Alice']
>>> lst_3
['Ann', 'Bob', 'Alice']To partially reverse a list Code: lstCode: lst[start:stop:-1]Here’s an example of some partial list reversals: Code: >>> lst = ['a', 'b', 'c', 'd', 'e']
>>> lst[5:2:-1]
['e', 'd']
>>> lst[:1:-1]
['e', 'd', 'c']
>>> lst[3:2:-1]
['d']All of those slicing operations reversed a subsequence of the original list. Note that the Code: startCode: stopPython List Reverse List Comprehension You can reverse a list with Python’s powerful list comprehension method. (Although I cannot imagine a scenario where this would actually make sense.) Related article: List comprehension is a compact way of creating lists. The simple formula is [ expression + context ].
For example, the expression Code: [x for x in range(3)]Code: [0, 1, 2]Here’s how you’d use list comprehension to reverse a list: Code: [lst[i] for i in range(len(lst)-1,-1,-1)]You go over all indices in negative order—starting with the last list index Code: len(lst)-1Code: range()Python List reverse() vs reversed() What’s the difference between the method Code: list.reverse()Code: reversed(list)
So you should use the former if you don’t want to create a new list and the latter if you want to create a new iterable without modifying the existing list. An example is the following: Code: >>> lst_1 = [1, 2, 3]
>>> lst_1.reverse()
>>> lst_1
[3, 2, 1]
>>> reversed(lst_1)
<list_reverseiterator object at 0x0000025B58FEC9B0>The output is not very intuitive but it only means that the Code: reversed()Python List Deep Reverse What if you want not only to reverse a list but running a deep reverse where all nested lists are also reversed in a recursive manner? Here’s how you can do it: Code: def deep_reverse(lst): ''' Reverses a nested list in place''' # Reverse top-level list lst.reverse() # Recursively reverse all nested lists for element in lst: if isinstance(element, list): deep_reverse(element) lst = [1, 2, 3, [4, 5, 6]]
deep_reverse(lst)
print(lst)This generates the output: Code: # OUTPUT: [[6, 5, 4], 3, 2, 1]Not only the first-level list is reversed but also the second-level list. The code is loosely inspired from this article. Python List Reverse Enumerate The Code: enumerate(list)You can reverse the order of enumerated tuples by stacking together the Code: enumerate()Code: list.reverse()Code: >>> for i, el in enumerate(list(reversed([1, 2, 3]))): print(i, el) 0 3
1 2
2 1This way, you first reverse the list which creates an iterator. You then transform it into a list. The result can be enumerated. If you want to reverse the order of the indices as well, simply switch the order of both functions: Code: >>> for i, el in reversed(list(enumerate([1, 2, 3]))): print(i, el) 2 3
1 2
0 1By first enumerating, you calculate the indices based on the original list. Then you reverse them in the outer function. Python List Reverse Iterator The Code: reversed(list)Code: list(...)Here’s an example: Code: >>> reversed([1, 2, 3])
<list_reverseiterator object at 0x0000021735E070B8>
>>> for i in reversed([1, 2, 3]): print(i) 3
2
1The iterator object doesn’t look pretty in the shell but it’s a more efficient way to iterate over a sequence of values than using lists. Why? Because lists need to maintain all values in memory. Iterators don’t. Python List Reverse Sort Do you want to sort a list in descending order? Use the Code: reverse=TrueCode: sorted()Code: >>> sorted([42, 1, 99])
[1, 42, 99]
>>> sorted([42, 1, 99], reverse=True)
[99, 42, 1]Rather than just using positive list indices, you can use reverse indexing in Python lists, too. The negative integer index -1 accesses the last element. The negative integer index -2 accesses the second last element and so on. Here’s an example: Code: >>> lst = ["Alice", "Bob", "Ann"]
>>> lst[-1] 'Ann'
>>> lst[-2] 'Bob'
>>> lst[-3] 'Alice'Do you want to iterate over a range of integer values in reverse order? Say, you want to iterate over the numbers from 10 to 0 in reverse order: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0. You can simply achieve this by specifying the Code: startCode: stopCode: stepCode: range(start, stop, step)Code: >>> for i in range(10, -1, -1): print(i) 10
9
8
7
6
5
4
3
2
1
0Note that the Code: startCode: stopPython List reverse() Doesn’t Work What if the Code: reverse()Code: list.reverse()Code: list.reverse()Code: NoneCode: listHere’s an example what you’re probably doing: Code: >>> lst = [1, 2, 3]
>>> print(lst)
[1, 2, 3]
>>> print(lst.reverse())
NoneIf you really want to have a new list with elements in reversed order, use the Python built-in Code: reversed(list)Code: >>> print(list(reversed([1, 2, 3])))
[3, 2, 1]The Code: reversed()Python Reverse List NumPy To reverse a NumPy array (or even a Python list), you can simply use slicing with negative step size Code: a[::-1]Code: >>> import numpy as np
>>> a = np.array([1, 2, 3])
>>> a[::-1]
array([3, 2, 1])Python List reverse() 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: reverse()In other words: can you call the Code: reverse()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.reverse()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. |