When we are working with lists, dictionaries, and sets in Python, we have a special syntax, called comprehensions. This feature helps us to improve the readability of our code, providing compact syntax for deriving a new list from another iterable.
Contents
List Comprehension
The following syntax is a common example of using for and makes some calculations, as you can notice, it will involve multiple statements.
1 2 3 4 5 6 7 |
my_list = [1, 2, 3, 4, 5, 6, 7, 8] added_one = [] for x in my_list: added_one.append(x + 1) print(added_one) |
Even, when the previous code is fully functional, with the irruption of comprehension lists, we are able to reduce the amount of code at the time that we improve the readability of the code.
1 2 3 4 |
my_list = [1, 2, 3, 4, 5, 6, 7, 8] added_one = [x + 1 for x in my_list] print(added_one) |
It is interesting to notice how compact is the new feature, but it is not all, we can add conditionals which can filter the expected results. The following modification to the original code will filter only the even numbers.
1 2 3 4 |
my_list = [1, 2, 3, 4, 5, 6, 7, 8] added_one = [x + 1 for x in my_list if (x % 2) == 0] print(added_one) |
On the other hand, it is important to mention that conditional can include a call to a function as in this example:
1 2 3 4 5 6 7 8 9 |
def is_even_number(number): if number % 2 == 0: return number my_list = [1, 2, 3, 4, 5, 6, 7, 8] added_one = [x + 1 for x in my_list if is_even_number(x)] print(added_one) |
The use of list comprehension is a complete substitute for loops, lambda functions as well as the functions map()
, filter()
and reduce()
.
About Walrus operator
In Python 3.8 was introduced the walrus operator, (:=), formally known as the assignment expression operator, allows us to assign variables in places where not allowed, for instance in conditional expression (if condition).
It can be expressed in the following way
name := expr
Here, the expr is evaluated and then assigned to the variable name. That value will also be returned. The following example shows you a simplistic but valid use of the walrus operator.
1 2 3 4 5 6 7 8 9 10 |
baseball_teams = { 'Yankees': 27, 'Cardinals': 11, 'Red Sox': 9, 'Athletics': 9, 'Giants': 8, } if (world_series_titles := baseball_teams.get('Cardinals', 0)): print(world_series_titles) |
As you can see, the use of the walrus operator is versatile and help us to reduce our code and compact as the comprehension list does.
Combining comprehension and Walrus operator
It is important to notice the fact of comprehension encompass lists, dictionary and sets. In the following example, we are going to combine the capacity of comprehension and use the walrus operator for the assignment. The example consists in get a dictionary with the top n of the championship for Major League Baseball (MLB), using a function which receives as a parameter the name of each team and returning only in case of being in the top n.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
from collections import Counter baseball_teams = { 'Yankees': 27, 'Cardinals': 11, 'Red Sox': 9, 'Athletics': 9, 'Giants': 8, 'Dodgers': 7, 'Pirates': 5, 'Reds': 5, 'Braves': 4, 'Tigers': 4, } n = 5 # number of top values def get_top_n(team_name, n): counter = Counter(baseball_teams) top_n = dict(counter.most_common(n)) return top_n.get(team_name, 0) top_n_winners = {name: x for name in baseball_teams if (x := get_top_n(name, n))} print(f"The top {n} championship teams are {top_n_winners}") |
Conclusion
I hope this article brings you a clear perspective about the possibilities that offer us comprehension and the walrus operator, giving us a clear, compact and non-repetitive way of working with Python. Happy Coding!