List Comprehensions β Creating Lists in One Line
After completing this topic, you will:
Know the list comprehension syntax, which turns 4 lines of a for loop into 1 line, and be able to use conditional filtering and dictionary comprehensions.
The Repetitive Pattern of for Loops
When creating lists, you often write code like this:
numbers = [1, 2, 3, 4, 5]squares = []for n in numbers: squares.append(n ** 2)
print(squares) # [1, 4, 9, 16, 25]It's 4 lines: create an empty list, loop with a for loop, and append. This pattern repeats. Python provides a syntax to reduce this to one line:
squares = [n ** 2 for n in numbers]This is a list comprehension.
Structure
[expression for item in iterable]How to read it: "Create a list by taking each item from the iterable, applying the expression, and using the result."
# Convert strings to uppercasenames = ['alice', 'bob', 'charlie']upper = [name.upper() for name in names]# ['ALICE', 'BOB', 'CHARLIE']
# String lengthlengths = [len(name) for name in names]# [5, 3, 7]
# From 1 to 10nums = [i for i in range(1, 11)]# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]Conditional Filtering β Adding if
[expression for item in iterable if condition]numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Only even numbersevens = [n for n in numbers if n % 2 == 0]# [2, 4, 6, 8, 10]
# Squares of numbers greater than 3big_squares = [n ** 2 for n in numbers if n > 3]# [16, 25, 36, 49, 64, 81, 100]if acts as a filter. Only items that meet the condition are included in the result.
In a for loop:
evens = []for n in numbers: if n % 2 == 0: evens.append(n)5 lines becomes 1 line.
if-else β Conditional Transformation
If you want to transform instead of filter, put if-else at the beginning:
# "Even" if even, "Odd" if oddlabels = ["even" if n % 2 == 0 else "odd" for n in range(1, 6)]# ['odd', 'even', 'odd', 'even', 'odd']The position matters:
- Filter (exclude):
[x for x in lst if condition]βifis at the end - Transformation (select):
[A if condition else B for x in lst]βif-elseis at the beginning
Dictionary Comprehension
Enclose it in curly braces to create a dictionary:
names = ['alice', 'bob', 'charlie']name_len = {name: len(name) for name in names}# {'alice': 5, 'bob': 3, 'charlie': 7}# Invert valuesoriginal = {'a': 1, 'b': 2, 'c': 3}flipped = {v: k for k, v in original.items()}# {1: 'a', 2: 'b', 3: 'c'}Set Comprehension
Curly braces + only the value creates a set:
words = ['hello', 'world', 'hello', 'python']unique_lengths = {len(w) for w in words}# {5, 6}Readability Warning
# This is okayresult = [x * 2 for x in range(10) if x % 2 == 0]
# This is hard to readresult = [f(x, y) for x in range(10) for y in range(10) if x != y if g(x, y) > threshold]If the comprehension can't fit in one line, or if there are nested for loops + 2 or more conditions, use a regular for loop instead. Shorter code isn't always better code. Readable code is good code.
Key Takeaway
List comprehension is the syntax
[expression for item in iterable if condition]to create lists in one line. Put the filterifat the end, and the conditional transformationif-elseat the beginning.{}+key: valueis a dictionary,{}+ only values is a set comprehension. If it doesn't fit in one line, use aforloop β readability comes first.