Python is famous for writing powerful logic in very few lines of code.
Two of the most important tools that make Python βPythonicβ are:
These tools are essential for writing clean, efficient, and readable code, especially when dealing with transformations, filtering, and data pipelines.
Today you will learn:
β The structure and syntax of list comprehensions
β How to add conditions inside comprehensions
β Nested comprehensions
β Difference between lists and generators
β How to write generator expressions
β When to use generators for performance
Letβs begin!
A list comprehension is a concise way to create a list using this pattern:
new_list = [expression for item in iterable]
Example: Square numbers from 1 to 5
squares = [x * x for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
This replaces a longer loop:
squares = []
for x in range(1, 6):
squares.append(x * x)
You can filter items by adding an if condition:
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
Example: Get names longer than 4 letters
names = ["Ali", "Mouad", "Sara", "Yassine"]
long_names = [n for n in names if len(n) > 4]
print(long_names)
Useful for flattening structures or creating grids.
matrix = [[1,2,3],[4,5,6],[7,8,9]]
flat = [num for row in matrix for num in row]
print(flat) # [1,2,3,4,5,6,7,8,9]
Equivalent to nested loops:
flat = []
for row in matrix:
for num in row:
flat.append(num)
Yes β comprehensions also work with dicts and sets.
squares = {x: x*x for x in range(5)}
print(squares)
Set comprehension:
unique_squares = {x*x for x in range(-3, 4)}
print(unique_squares)
A generator expression looks like a list comprehension but uses parentheses instead of brackets:
gen = (x * x for x in range(1, 6))
gen = (x * x for x in range(1, 6))
for value in gen:
print(value)
Generator expressions are excellent for large datasets, streams, and files.
Use a generator when:
Examples:
β Reading a huge file line by line
β Streaming data from an API
β Processing logs
Create a list of the cubes of numbers from 1 to 10.
Given:
names = ["Ali", "Sara", "Amine", "Yassine", "Amina"]
Create a list containing only names that start with "A".
nested = [[1, 2], [3, 4], [5, 6]]
Output should be: [1, 2, 3, 4, 5, 6].
Create:
{1:1, 2:4, 3:9, 4:16}
List comprehensions and generator expressions are two of the most powerful tools in Python. They help you:
Mastering these techniques is essential for writing professional, Pythonic code.