Python Advanced: List & Dictionary Comprehensions

Goal of the Day

Today you will learn:

By the end, you will be able to create complex lists and dictionaries much faster and cleaner.

Step 1: What is a Comprehension?

A comprehension is a shorthand for loops.

Instead of:


numbers = [1,2,3,4,5]
squares = []

for x in numbers:
    if x % 2 == 1:
        squares.append(x*x)

You can write:


squares = [x*x for x in numbers if x % 2 == 1]

👉 Same functionality, but much shorter and clearer

Step 2: Understanding List Comprehensions


numbers = [1,2,3,4,5]
squares = [x*x for x in numbers if x % 2 == 1]

print(squares)

Output:


[1, 9, 25]

Structure:


[x*x for x in numbers if x % 2 == 1]

Step 3: More Examples

Double all numbers:


numbers = [1,2,3]
new_list = [x*2 for x in numbers]
print(new_list)

Output:


[2, 4, 6]

Only even numbers:


numbers = [1,2,3,4,5]
evens = [x for x in numbers if x % 2 == 0]
print(evens)

Output:


[2, 4]

Step 4: Dictionary Comprehensions


names = ["Max","Anna","Tom"]
ages = [20,25,30]

person_dict = {names[i]: ages[i] for i in range(len(names))}

print(person_dict)

Output:


{"Max": 20, "Anna": 25, "Tom": 30}

Better variant using zip():


person_dict = {name: age for name, age in zip(names, ages)}

Step 5: More Examples


numbers = [1,2,3,4]

squares_dict = {x: x*x for x in numbers}

print(squares_dict)

Output:


{1: 1, 2: 4, 3: 9, 4: 16}

Step 6: Combine with Conditions


numbers = [1,2,3,4,5]

even_squares = {x: x*x for x in numbers if x % 2 == 0}

print(even_squares)

Output:


{2: 4, 4: 16}

Practice Tips

Exercise 1: Even Numbers

Create a list of all even numbers from 1 to 20:


numbers = [x for x in range(1,21) if x % 2 == 0]

Exercise 2: Dictionary with Squares

Create a dictionary with numbers from 1 to 5 and their squares:


squares = {x: x*x for x in range(1,6)}