Today you will learn:
By the end, you will be able to create complex lists and dictionaries much faster and cleaner.
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
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]
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]
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)}
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}
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}
Create a list of all even numbers from 1 to 20:
numbers = [x for x in range(1,21) if x % 2 == 0]
Create a dictionary with numbers from 1 to 5 and their squares:
squares = {x: x*x for x in range(1,6)}