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

Integrating Azure Blob Storage with Snowflake on AWS: A Guide to Storage Integration and Staging Data

This article offers a comprehensive, step-by-step guide for integrating Azure Blob Storage with a Snowflake…

6 days ago

Getting Started with SnowSQL: Connecting to Your Snowflake Account

In this quick guide, we’ll walk through the essential steps to connect to Snowflake using…

3 weeks ago

A new step in my career as a Senior Data Architect

I am thrilled to share that I have embarked on a new professional journey as…

5 months ago

Data Modeling and its relevance in the Cloud Era

Since 2005, I've immersed myself in the dynamic world of data and its modeling. It's…

6 months ago

Formatting our Postgres scripts with pgformatter in DBeaver

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

11 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…

12 months ago