Lesson 6.4: List Comprehensions
By the end of this lesson, you will be able to:
- Write list comprehensions to create lists concisely
- Add conditions to filter elements in comprehensions
- Convert between traditional for-loops and list comprehensions
- Know when to use comprehensions vs. traditional loops
What is a List Comprehension?
List Comprehension: A concise, one-line way to create a new list by applying an expression to each item in an existing sequence. Syntax:
[expression for item in iterable]
List comprehensions let you create lists in a single line of code. They are one of Python's most popular features because they make code shorter and more readable for simple transformations.
Traditional Loop vs. List Comprehension
# Traditional for-loop approach squares = [] for n in range(1, 6): squares.append(n ** 2) print(squares) # Same thing with a list comprehension squares = [n ** 2 for n in range(1, 6)] print(squares)
[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]
Breaking Down the Syntax
A list comprehension has three parts:
[expression for item in iterable]
- expression -- what to do with each item (e.g.,
n ** 2) - for item in iterable -- the loop that generates items
Basic List Comprehensions
# Convert temperatures from Celsius to Fahrenheit celsius = [0, 10, 20, 30, 40] fahrenheit = [c * 9/5 + 32 for c in celsius] print(fahrenheit) # Make all names uppercase names = ["alice", "bob", "charlie"] upper_names = [name.upper() for name in names] print(upper_names) # Get the length of each word words = ["hello", "world", "python"] lengths = [len(word) for word in words] print(lengths)
[32.0, 50.0, 68.0, 86.0, 104.0]
['ALICE', 'BOB', 'CHARLIE']
[5, 5, 6]
List Comprehensions with Conditions
You can add an if condition to filter which items are included in the new list.
Syntax: [expression for item in iterable if condition]
# Get only even numbers numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] evens = [n for n in numbers if n % 2 == 0] print(evens) # Get words longer than 4 characters words = ["hi", "hello", "hey", "howdy", "greetings"] long_words = [w for w in words if len(w) > 4] print(long_words) # Get passing scores scores = [45, 82, 93, 67, 55, 78, 91] passing = [s for s in scores if s >= 70] print(passing)
[2, 4, 6, 8, 10]
['hello', 'howdy', 'greetings']
[82, 93, 78, 91]
Combining Transformation and Filtering
# Square only the even numbers numbers = list(range(1, 11)) even_squares = [n ** 2 for n in numbers if n % 2 == 0] print(even_squares)
[4, 16, 36, 64, 100]
Comprehensions with if/else
To use an if/else expression (where you want different values based on a condition), the syntax changes -- the condition goes before the for.
# Label numbers as "even" or "odd" numbers = [1, 2, 3, 4, 5] labels = ["even" if n % 2 == 0 else "odd" for n in numbers] print(labels) # Pass or fail scores = [85, 42, 91, 67, 55] results = ["Pass" if s >= 60 else "Fail" for s in scores] print(results)
['odd', 'even', 'odd', 'even', 'odd']
['Pass', 'Fail', 'Pass', 'Pass', 'Fail']
Syntax Difference: Filtering vs. Transforming
- Filtering (if only):
[x for x in list if condition]-- condition goes at the END - Transforming (if/else):
[A if condition else B for x in list]-- condition goes at the BEGINNING
Practical Examples
Example 1: Processing a List of Names
names = [" alice ", "BOB", " Charlie", "diana "] # Clean up: strip whitespace and capitalize clean_names = [name.strip().title() for name in names] print(clean_names)
['Alice', 'Bob', 'Charlie', 'Diana']
Example 2: Extracting Data
# Extract first letters words = ["Python", "Is", "Fun"] initials = [word[0] for word in words] print(initials) print("".join(initials))
['P', 'I', 'F']
PIF
Example 3: Working with Numbers
# Create a multiplication table row row_5 = [5 * i for i in range(1, 11)] print("5x table:", row_5)
5x table: [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
When to Use List Comprehensions
Rule of Thumb: Use list comprehensions when the logic is simple and fits on one line. Use traditional for-loops when the logic is complex, involves multiple steps, or when readability suffers.
Good Uses
# Simple transformation doubled = [x * 2 for x in range(10)] # Simple filter positives = [x for x in numbers if x > 0] # Simple string operation lower_names = [name.lower() for name in names]
When to Stick with For-Loops
# Complex logic -- use a regular loop instead results = [] for item in data: if item > 0: processed = item ** 2 + 1 if processed < 100: results.append(processed) # Side effects (printing, writing files) -- use a loop for name in names: print(f"Hello, {name}!")
Try It Yourself
Write a list comprehension that creates a list of the first 10 cube numbers (1, 8, 27, 64, ...). Then write another that filters this list to only include cubes less than 100.
Check Your Understanding
- Rewrite this loop as a list comprehension:
result = []; for x in range(10): result.append(x * 3) - What does
[x for x in range(20) if x % 5 == 0]produce? - Write a comprehension that converts
["hello", "world"]to["HELLO", "WORLD"].
result = [x * 3 for x in range(10)][0, 5, 10, 15](multiples of 5 from 0 to 19)[word.upper() for word in ["hello", "world"]]
Key Takeaways
- List comprehensions provide a concise way to create lists:
[expr for item in iterable] - Add a filter with
if:[expr for item in iterable if condition] - Use if/else for transformations:
[A if cond else B for item in iterable] - Comprehensions are best for simple, one-line operations
- Use traditional loops for complex logic or side effects
- Readability matters -- if a comprehension is hard to read, use a loop instead