03-24-2020, 05:14 PM
Python List count()
This tutorial shows you everything you need to know to help you master the essential method of the most fundamental container data type in the Python programming language.
Definition and Usage:
The method counts the number of occurrences of the element in the .
Here’s a short example:
In the first line of the example, you create the list. You then count the number of times the integer values 42 and 2 appear in the list.
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/@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:
Arguments:
Argument |
Description
|
Counts the number of occurrences of in . A value appears in the list if the operator returns .
Return value: The method returns an integer value set to the number of times the argument appears in the list. If the value does not appear in the list, the return value is 0.
Python 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 operation is O(n) for a list with n elements. The standard Python implementation cPython“touches” all elements in the original list to move them to another position. Thus, the time complexity is linear in the number of list elements.
You can see a plot of the time complexity of the method for growing list size here:
![[Image: image-25.png]](https://blog.finxter.com/wp-content/uploads/2020/03/image-25.png)
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:
Python List reverse() In Place
If you call the method on any list object in Python, it reverses the list elements of this particular list object. You say that the reverse method happens in place.
This is a common mistake of many Python beginners. They assume that the method creates a new list with the elements in reversed order. This is not the case: the method modifies only the existing list object.
You can see this in the following example:
In the example, you only reversed the existing list. But you didn’t create a new list!
Python List reverse() None
The return value of the method is . Why? Because the method reverses the list in place. This means that no new list is created. Instead, the method modifies the old list object.
You’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
|
Reverses the order of the elements of list in place.
|
The built-in method creates a new list object with reversed list elements.
|
Slicing with negative indexing is the most concise way of reversing the order of a list. It creates a new list object.
|
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:
Let’s check if it does what it’s supposed to do (reversing the list):
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!![[Image: 1f609.png]](https://s.w.org/images/core/emoji/12.0.0-1/72x72/1f609.png)
Python List Reverse Slice
Slicingis the easiest way to reverse a list.
To reverse the list, you simply use slicing operation with default and indices (not given) and negative step size (given).
There’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 method which reverses the list in place.
Here’s an example of slicing to reverse a given list:
You see that the two lists and are independent objects in memory because the slicing operation creates a new list.
Related 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:
Python List Partial Reverse
To partially reverse a list, use slicing with negative step size: . The start and stop values define the part of the list to be reversed and the step size -1 means that you go through the list in reversed order.
Here’s an example of some partial list reversals:
All of those slicing operations reversed a subsequence of the original list. Note that the index must be larger or equal than the index because you traverse the list in negative order (well, if you don’t want to have an empty slice object).
Python 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 creates the list .
Here’s how you’d use list comprehension to reverse a list:
You go over all indices in negative order—starting with the last list index and ending in the first list index 0. Note that the stop index is not included in the index sequence so I used the value -1 as the stop index for the built-in function.
Python List reverse() vs reversed()
What’s the difference between the method and the built-in function ?
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:
The output is not very intuitive but it only means that the function returns an iterable object.
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:
This generates the output:
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 built-in function returns a list of tuples with the first tuple value being the list index and the second tuple value being the list element.
You can reverse the order of enumerated tuples by stacking together the function and the method as follows:
This 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:
By first enumerating, you calculate the indices based on the original list. Then you reverse them in the outer function.
Python List Reverse Iterator
The method returns an iterator, not a new list. This is different: an iterator is more efficient than a list. You can easily convert the iterator object into a list by using the built-in function.
Here’s an example:
The 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 argument of the method. Here’s an example:
Python List reverse() Index
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:
Python List Reverse range()
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, , and arguments of the method:
Note that the argument is included in the range but the argument isn’t.
Python List reverse() Doesn’t Work
What if the method doesn’t work? Chances are that you assume the method has a return value—that is the reversed list. This is not the case! The method returns because it reverses the in place. It doesn’t return a new reversed list.
Here’s an example what you’re probably doing:
If you really want to have a new list with elements in reversed order, use the Python built-in method:
The method reverses the list and returns the reversed list as an iterator object. You need to convert it to a list first before printing it to the shell (and receiving a meaningful output).
Python Reverse List NumPy
To reverse a NumPy array (or even a Python list), you can simply use slicing with negative step size. Here’s an example:
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) are actually thread safe.
In other words: can you call the 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 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 method reverses the order of the list elements.
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.
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()![[Image: image-25.png]](https://blog.finxter.com/wp-content/uploads/2020/03/image-25.png)
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:
- The lambda function creates an anonymous function with argumentCode:
lambda x: yand return valueCode:x. You can read the detailed tutorial on the Finxter blog.Code:y
- List concatenation creates the new listCode:
[a, b, c] + [d]. You can read the detailed tutorial on the Finxter blog.Code:[a, b, c, d]
- Slicing carves out a subsequence from the list between theCode:
lst[start:stop]andCode:startindices. You can read the detailed tutorial on the Finxter blog.Code:stop
- The ternary operator returns the valueCode:
x if y else zifCode:xisCode:y. In all other cases, it returns the valueCode:True. You can read the detailed tutorial on the Finxter blog.Code:z
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!
![[Image: 1f609.png]](https://s.w.org/images/core/emoji/12.0.0-1/72x72/1f609.png)
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:
- Use slicing , orCode:
list[::-1]
- Call themethod and convert the result to a list using theCode:
reversed(list)constructor.Code:list(...)
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 ].
- 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.
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)- modifies an existing list in place and reverses the order of elements in this list object. No new list object is created.Code:
list.reverse()
- creates a new iterable object by reversing the order of elements of the originalCode:
reversed(list).Code: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.

