List Comprehension
Comprehension offers a shorter syntax when we want to create a new object based on an old one, a condition, or a function. List comprehension provides a concise way to create lists.
Basic Syntax
The general form of list comprehension is:
[expression for var in iter [if condition][...list comp]]Where:
expressionis the value to include in the listvaris the variable that iterates over the iterableiteris the iterable (list, range, etc.)if conditionis optional - filters elements- Additional list comprehensions are optional - for nested iterations
Simple List Comprehension
The simplest form creates a list by applying an expression to each element:
list1 = [n * 2 for n in range(3)]print(list1) # [0, 2, 4]This is equivalent to:
list1 = []for n in range(3): list1.append(n * 2)List Comprehension with Condition
You can add a condition to filter elements:
list2 = [n * 2 for n in range(3) if n > 0]print(list2) # [2, 4]This only includes elements where n > 0, so it skips n = 0.
Copying a List
You can use list comprehension to create a copy of a list:
list1 = [0, 2, 4]list3 = [n for n in list1]print(list3) # [0, 2, 4]Nested List Comprehension
You can use multiple for clauses to create nested iterations:
list1 = [0, 2, 4]list2 = [2, 4]list4 = [[m, n] for m in list1 for n in list2]print(list4) # [[0, 2], [0, 4], [2, 2], [2, 4], [4, 2], [4, 4]]This creates all combinations of elements from list1 and list2.
Multiple Conditions
You can have multiple conditions and multiple loops:
list5 = [m + n for m in range(-4, 4) if m % 2 == 0 for n in range(-4, 4) if n % 2 == 1]print(list5) # [-7, -5, -3, -1, -5, -3, -1, 1, -3, -1, 1, 3, -1, 1, 3, 5]This:
- Iterates over
mfrom -4 to 3, but only whenm % 2 == 0(even numbers) - For each
m, iterates overnfrom -4 to 3, but only whenn % 2 == 1(odd numbers) - Adds
m + nfor each valid combination
Exercises
Exercise 1: Basic List Comprehension
Use list comprehension to create a list of squares of numbers from 0 to 9.
Basic List Comprehension
squares = [n * n for n in range(10)]print(squares)Exercise 2: List Comprehension with Condition
Use list comprehension to create a list of even numbers from 0 to 20.
List Comprehension with Condition
evens = [n for n in range(21) if n % 2 == 0]print(evens)Exercise 3: Transforming Elements
Given a list of strings, use list comprehension to create a list of their lengths.
Transforming Elements
n = int(input())words = []for i in range(n): words.append(input())
lengths = [len(word) for word in words]print(lengths)Exercise 4: Nested List Comprehension
Use nested list comprehension to create a list of all pairs (i, j) where i is from 0 to 2 and j is from 0 to 2.
Nested List Comprehension
pairs = [(i, j) for i in range(3) for j in range(3)]print(pairs)Exercise 5: Multiple Conditions
Use list comprehension to create a list of numbers from 1 to 50 that are divisible by both 3 and 5.
Multiple Conditions
numbers = [n for n in range(1, 51) if n % 3 == 0 and n % 5 == 0]print(numbers)