Categories: Python

List Comprehension and Walrus operator in Python

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.

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.

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.

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.

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:

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.

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.

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!

geohernandez

Share
Published by
geohernandez

Recent Posts

Formatting our Postgres scripts with pgformatter in DBeaver

Are you a PostgreSQL enthusiast using DBeaver on a Windows Platform? If you find yourself…

4 months ago

Looking back to Kimball’s approach to Data Warehousing

Over time, it's fascinating to witness how certain concepts, approaches, or visions age. Time, in…

5 months ago

Playing with some Pandas functions and Airflow operators

Recently, I was dealing with a task where I had to import raw information into…

11 months ago

Using interpolated format strings in Python

The release of Python 3.6 came with exciting functionalities. I want to speak about the…

1 year ago

Getting the last modified directory with Python

Working with os paths is a prevalent task, especially when working on a console application…

1 year ago

First steps for configuring SQL Server with Docker

Sometimes, our working habits could experiment some interesting changes, maybe forced by real needs or…

2 years ago