Chapter 6: Data Structures / Lesson 33

List Comprehensions

Introduction to List Comprehensions

List comprehensions provide a concise, readable way to create lists based on existing iterables. They're more Pythonic than traditional loops for creating lists and are often faster and more elegant.

List comprehensions combine the power of loops and conditional statements into a single line, making your code more compact and easier to read once you understand the syntax.

Basic Syntax

The basic syntax is: [expression for item in iterable]. This creates a new list by applying the expression to each item in the iterable.

basic_comprehension.py
# Traditional loop squares = [] for x in range(1, 6): squares.append(x ** 2) print(squares) # [1, 4, 9, 16, 25] # List comprehension (equivalent) squares = [x ** 2 for x in range(1, 6)] print(squares) # [1, 4, 9, 16, 25] # More examples numbers = [x * 2 for x in range(5)] print(numbers) # [0, 2, 4, 6, 8] words = [word.upper() for word in ["hello", "world"]] print(words) # ['HELLO', 'WORLD']

With Conditions

You can add conditions using if to filter items: [expression for item in iterable if condition]

with_conditions.py
# Filter even numbers evens = [x for x in range(10) if x % 2 == 0] print(evens) # [0, 2, 4, 6, 8] # Filter positive numbers numbers = [-2, -1, 0, 1, 2, 3] positive = [x for x in numbers if x > 0] print(positive) # [1, 2, 3] # Filter words longer than 3 characters words = ["cat", "dog", "elephant", "bat"] long_words = [w for w in words if len(w) > 3] print(long_words) # ['elephant']

Nested Comprehensions

You can nest comprehensions to create lists of lists or work with nested structures:

nested.py
# Create a multiplication table table = [[i * j for j in range(1, 4)] for i in range(1, 4)] print(table) # [[1, 2, 3], [2, 4, 6], [3, 6, 9]] # Flatten a nested list nested = [[1, 2], [3, 4], [5]] flat = [item for sublist in nested for item in sublist] print(flat) # [1, 2, 3, 4, 5]

When to Use Comprehensions

✅ Use List Comprehensions When:

• Creating a new list from an existing iterable

• The logic is simple and fits on one line

• You want more readable, Pythonic code

• Performance matters (comprehensions are often faster)

💡 Use Traditional Loops When:

• The logic is complex and needs multiple lines

• You need side effects (like printing during iteration)

• Readability would suffer from a comprehension

🎉

Lesson Complete!

Great work! Continue to the next lesson.

main.py
📤 Output
Click "Run" to execute...