Python Comprehensions

PythonBeginner
Practice Now

Introduction

In this lab, you will be introduced to Python comprehensions, a special syntax that allows you to create data structures like lists, sets, and dictionaries from other iterables in a very concise way. Comprehensions are incredibly useful when dealing with one or two levels of nested for loops, making your code more readable and often more efficient.

You will start with the most common type, list comprehensions, and see how they compare to traditional for loops. Then, you will learn to add conditional logic to filter elements or transform them. Finally, you will see how the same principles apply to creating sets and dictionaries.

List comprehension

In this step, you will learn the basic syntax of list comprehensions as a concise way to create lists from other iterables. We will compare the traditional for-loop approach with the more elegant list comprehension syntax.

Note: If you are not familiar with using WebIDE (VS Code like), please learn it first at this lab.

First, let's look at how we would create a new list from an existing one using a standard for loop.

Open the main.py file from the file explorer on the left. Copy and paste the following code into the file:

## Traditional approach: create list using a for loop
names = ['Charles', 'Susan', 'Patrick', 'George']

new_list = []
for n in names:
    new_list.append(n)

print(new_list)

To run the code, open a terminal by clicking the + icon in the terminal panel and selecting "New Terminal". Then, execute the following command:

python3 main.py

You will see the following output:

['Charles', 'Susan', 'Patrick', 'George']

Now, let's achieve the same result using a list comprehension. The basic syntax is [expression for item in iterable].

Replace the content of main.py with the following code:

## List comprehension: concise way to create a new list
## Syntax: [expression for item in iterable]
names = ['Charles', 'Susan', 'Patrick', 'George']

new_list = [n for n in names]  ## Create list with all names
print(new_list)

Run the script again:

python3 main.py

The output is identical, but the code is much shorter and more descriptive.

['Charles', 'Susan', 'Patrick', 'George']

List comprehensions can also handle nested loops. For example, to create a list of tuples from two ranges, you can do the following.

Update your main.py file with this code and run it.

## Nested list comprehension: create tuples from two ranges
## Equivalent to nested for loops
n = [(a, b) for a in range(1, 3) for b in range(1, 3)]
print(n)

Run the script:

python3 main.py

The output will be a list of all possible tuple combinations:

[(1, 1), (1, 2), (2, 1), (2, 2)]

Adding conditionals

In this step, you will explore how to incorporate conditional logic into list comprehensions. You will learn to filter elements using an if statement and how to apply conditional expressions to each element using an if-else structure.

Let's say we want to create a new list containing only the names that start with the letter 'C'. With a traditional for loop, you would add an if statement inside the loop.

Update your main.py with the following code:

## Traditional approach: filter with if condition
names = ['Charles', 'Susan', 'Patrick', 'George', 'Carol']

new_list = []
for n in names:
    if n.startswith('C'):  ## Filter names starting with 'C'
        new_list.append(n)

print(new_list)

Run the script to see the result:

python3 main.py

Output:

['Charles', 'Carol']

To do this with a list comprehension, you add the if statement at the end. The syntax is [expression for item in iterable if condition].

Try this in your main.py:

## List comprehension with condition: filter items
## Syntax: [expression for item in iterable if condition]
names = ['Charles', 'Susan', 'Patrick', 'George', 'Carol']
new_list = [n for n in names if n.startswith('C')]
print(new_list)

Run it, and you will get the same filtered list:

python3 main.py

Output:

['Charles', 'Carol']

You can also use an if-else statement to perform a conditional action on every element. In this case, the if-else expression comes before the for loop. The syntax is [expression_if_true if condition else expression_if_false for item in iterable].

Let's create a new list that doubles even numbers but keeps odd numbers as they are. Update main.py with the following code and run it.

## List comprehension with if-else: conditional expression
## Syntax: [expression_if_true if condition else expression_if_false for item in iterable]
nums = [1, 2, 3, 4, 5, 6]
new_list = [num*2 if num % 2 == 0 else num for num in nums]  ## Double even numbers
print(new_list)

Run the script:

python3 main.py

The output shows that only the even numbers have been doubled:

[1, 4, 3, 8, 5, 12]

Set comprehension

In this step, you will understand how to apply the comprehension syntax to create sets. The basics of list comprehensions also apply to sets and dictionaries.

Set comprehensions are very similar to list comprehensions. The main difference is that they use curly braces {} instead of square brackets [] and produce a set, which is an unordered collection of unique elements.

The syntax is {expression for item in iterable}.

Let's create a set from another set, converting all its string elements to uppercase. Update your main.py file with the following code:

## Set comprehension: create a set using comprehension syntax
## Syntax: {expression for item in iterable}
b = {"abc", "def"}
upper_set = {s.upper() for s in b}  ## Convert all strings to uppercase
print(upper_set)

Now, run the script:

python3 main.py

The output will be a new set containing the uppercase strings. Note that since sets are unordered, the order of elements in the output may vary.

{'DEF', 'ABC'}

If the original iterable had duplicate items, the resulting set would only contain the unique elements, as sets automatically discard duplicates.

Dict comprehension

In this step, you will learn to construct dictionaries using dictionary comprehensions. Like set comprehensions, they also use curly braces {}, but they require a key-value pair separated by a colon.

The syntax is {key_expression: value_expression for item in iterable}.

A common use case is to create a new dictionary by transforming or swapping the key-value pairs of an existing dictionary. Let's try swapping the keys and values of a dictionary.

Update your main.py file with the following code:

## Dict comprehension: swap keys and values
## Syntax: {key_expression: value_expression for item in iterable}
c = {'name': 'Pooka', 'age': 5}
swapped_dict = {v: k for k, v in c.items()}  ## Reverse key-value pairs
print(swapped_dict)

Run the script:

python3 main.py

The output will be a new dictionary where the original values are now keys, and the original keys are values.

{'Pooka': 'name', 5: 'age'}

You can also use comprehensions to create other data types from dictionaries. For example, here is how you can use a list comprehension to generate a list of formatted strings from a dictionary's items.

Replace the code in main.py with this example and run it:

## List comprehension from dictionary: create formatted strings
c = {'name': 'Pooka', 'age': 5}
formatted_list = ["{}:{}".format(k.upper(), v) for k, v in c.items()]  ## Format as "KEY:value"
print(formatted_list)

Run the script:

python3 main.py

This will produce a list of strings, not a dictionary.

['NAME:Pooka', 'AGE:5']

This demonstrates the flexibility of using comprehensions to process and transform different data structures. For your final task in this step, please ensure your main.py contains the dictionary-swapping code.

Summary

In this lab, you've learned how to use Python's powerful comprehension syntax to create lists, sets, and dictionaries in a concise and readable way.

You started with list comprehensions, seeing how they provide a more elegant alternative to traditional for loops. You then learned how to add conditional logic, using a trailing if for filtering and an if-else expression for transforming elements. Finally, you saw how these same principles apply to set and dict comprehensions, using curly braces {} to build sets of unique items and dictionaries of key-value pairs.

Comprehensions are a fundamental part of idiomatic Python code. Mastering them will make your code more efficient and elegant. Keep practicing to make them a natural part of your Python programming toolkit.