geohernandez
Menu
  • HOME
  • ABOUT
  • CONTACT ME
  • WORK WITH GEO
    • Data Specialist
    • Speaker Events
    • Resume
  • English
    • English
    • Español
Menu

List Comprehension and Walrus operator in Python

Posted on August 15, 2023August 16, 2023 by geohernandez

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
  • About Walrus operator
  • Combining comprehension and Walrus operator
  • Conclusion

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.

Python
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.

comprenhension list example
Python
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.

Python
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:

Python
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.

Python
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.

Python
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!

Category: Python

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Search for articles

Recent Posts

  • Quick Guide: BigQuery Service Account Setup Using gcloud
  • The Art of Data Modeling in AI times
  • Getting Started with Snowflake’s Snowpipe for Data Ingestion on Azure

Categories

  • Airflow (1)
  • Azure (6)
  • Azure DevOps (2)
  • Bash script (1)
  • Blog (1)
  • Cassandra (3)
  • Chronicles from the trenches (26)
  • Data Architecture (3)
  • Data Engineering (11)
  • DB optimization (2)
  • Events (2)
  • GIT (1)
  • MySQL (1)
  • Python (7)
  • Snowflake (3)
  • SQL Saturday (1)
  • SSIS (2)
  • T-SQL (5)
  • Uncategorized (2)

Archives

  • May 2025 (1)
  • March 2025 (1)
  • January 2025 (2)
  • October 2024 (1)
  • July 2024 (1)
  • May 2024 (1)
  • December 2023 (1)
  • November 2023 (1)
  • August 2023 (1)
  • June 2023 (1)
  • December 2022 (1)
  • November 2022 (1)
  • July 2022 (1)
  • March 2022 (1)
  • September 2021 (1)
  • May 2021 (1)
  • March 2021 (1)
  • February 2021 (3)
  • December 2020 (1)
  • October 2020 (3)
  • September 2020 (1)
  • August 2020 (1)
  • January 2020 (1)
  • August 2019 (1)
  • July 2019 (1)
  • June 2019 (1)
  • May 2019 (1)
  • April 2019 (1)
  • March 2019 (1)
  • November 2018 (3)
  • October 2018 (1)
  • September 2018 (1)
  • August 2018 (2)
© 2025 geohernandez | Powered by Minimalist Blog WordPress Theme