Basics

7 Useful List Comprehensions You Didn’t Think Of

What will you learn?

Once you understand list comprehension they actually improve your code readability – still I often advice to comment what the list comprehension does.

First I will show you what List Comprehension is and how the basic case works including with an enclosed if-statement. Then I am going through the 7 use cases you din’t think of and some final thoughts and an alternatives.

What is List Comprehension?

A list comprehension in Python includes three elements.

  1. Expression The member itself, a call to a method, or any other valid expression that returns a value. In the example above, the expression i * i is the square of the member value.
  2. Member The object or value in the list or iterable. In the example above, the member value is i.
  3. Iterable A list, set, sequence, generator, or any other object that can return its elements one at a time. In the example above, the iterable is range(10).

I like to show some examples to explain it better. A List Comprehension is on the following form.

my_list = [do_this(element) for element in this_list]

Instead of this.

my_list = []
for element in this_list:
    my_list.append(element)

A List Comprehension with if-statement.

my_list = [do_this(element) for element in this_list if this_is_true(element)]

Instead of this.

my_list = []
for element in this_list:
    if this_is_true(element):
        my_list.append(element)

Now let’s go through the 7 use cases you didn’t think of.

#1 List Comprehension for Filtering

Say you want to filter all temperatures between 30 and 34 degrees (both excluded here).

temperaturs = [12, 32, 34, 36, 34, 12, 32]

filtered_temps = [t for t in temperaturs if 34 > t > 30]

This will give the items [32, 32] in filtered_temps.

Another example would to find all the strings that are digits.

alphanumeric = ["47", "abcd", "21st", "n0w4y", "test", "55123"]

filtered_aphanumeric = [int(string) for string in alphanumeric if string.isdigit()]

This will give the items [47, 55123]. Notice that we also convert them to integers.

#2 Combining Lists

If you have two lists and you want to combine all combinations from each list.

colors = ["red", "blue", "black"]
models = ["12", "12 mini", "12 Pro"]

combined = [(model, color) for model in models for color in colors]

This will give the following list in combined.

[('12', 'red'),
 ('12', 'blue'),
 ('12', 'black'),
 ('12 mini', 'red'),
 ('12 mini', 'blue'),
 ('12 mini', 'black'),
 ('12 Pro', 'red'),
 ('12 Pro', 'blue'),
 ('12 Pro', 'black')]

A list of tuples of all combinations. If you want to become better at working with strings in Python check this guide.

#3 Finding common elements

Imagine you have two lists and you want to find the elements which are in both lists.

students_a = ["Anna", "Elsa", "Tanja", "Freja", "Frigg"]
students_b = ["Ranja", "Natascha", "Anna", "Tanja"]

common = [student for student in students_a if student in students_b]

This will give you the following items in common.

['Anna', 'Tanja']

#4 Combining Elements with the Same Position

Imagine you have multiple lists with elements that are connected by position.

names = ["John", "Mary", "Lea"]
surnames = ["Smith", "Wonder", "Singer"]
ages = ["22", "19", "25"]

combined = [F"{name} {surname} - {age}" for name, surname, age in zip(names, surnames, ages)]

Then combined will be as follows.

['John Smith - 22', 'Mary Wonder - 19', 'Lea Singer - 25']

Also check out how zip can be used and other built-in functions in Python.

#5 Convert Values

Say you have a list of elements that all need to be converted. Using a function for the conversion can be convenient and also make the transformation of the list easy with List Comprehension.

def convert_to_dol(eur):
    return round(eur * 1.19, 2)


prices = [22.30, 12.00, 0.99, 1.10]
dollar_prices = [convert_to_dol(price) for price in prices]

This will give the following values in dollars_prices.

[26.54, 14.28, 1.18, 1.31]

#6 Frequency Count

I love this one. It is done on a Dict Comprehension, but is useful in many cases.

string = 'this is my string of letters that we will count'

freq = {c: string.count(c) for c in set(string)}

This will give the following dictionary in freq.

{'w': 2, 'n': 2, 'u': 1, 'e': 3, 't': 7, 'r': 2, 'h': 2, 'o': 2, 'm': 1, 'f': 1, 'i': 4, 's': 4, 'y': 1, 'l': 3, ' ': 9, 'a': 1, 'c': 1, 'g': 1}

#7 Generators

Generators are a great tool to master and can be combined with List Comprehension.

def return_next():
    for i in range(10):
        yield i
        
my_list = [i for i in return_next()]

This is a simple example but the power should not be underestimated from it.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Final thoughts on List Comprehension

List Comprehension is one of the most popular paradigms in Python. That said, you should always keep readability in mind. If you create long and non-intuitive List Comprehensions, maybe you should construct it in another way. Your goal is to create easy to undrestand code – not complex code.

If you want to see a great use case of List Comprehension – then check out how to make a Word Cloud.

Want to learn more?

If this is something you like and you want to get started with Python, then check my 8 hours FREE video course with full explanations, projects on each levels, and guided solutions.

The course is structured with the following resources to improve your learning experience.

  • 17 video lessons teaching you everything you need to know to get started with Python.
  • 34 Jupyter Notebooks with lesson code and projects.
  • A FREE 70+ pages eBook with all the learnings from the lessons.

See the full FREE course page here.

Rune

Share
Published by
Rune

Recent Posts

Learn Python FREE Online

Why learn Python? There are many reasons to learn Python, and that is the power…

3 days ago

How to Check if a Number is Even or Odd with Python

What will you learn? How to use the modulo operator to check if a number…

1 week ago

The Truth About Being a Python Software Contractor

There are a lot of Myths out there There are lot of Myths about being…

2 months ago

Do This and 10X Your Salary as a Software Engineer

To be honest, I am not really a great programmer - that is not what…

2 months ago

Ultimate Guide to the Data Science Career Path

What does it take to become a Data Scientist? Data Science is in a cross…

2 months ago

How to Setup a MySQL Server in Docker for Your Python Project

What will you learn? Need to setup a SQL server? You don’t need to install…

4 months ago