intermediate

List Comprehensions

Write concise loops using Python list comprehensions.

List comprehensions are a powerful Python feature that lets you create lists in a single line of code. They combine the functionality of for loops with the elegance of functional programming. Once you master list comprehensions, you will write cleaner, more Pythonic code that is often faster than traditional loops.

📚 Concepts & Theory

Basic List Comprehension:

# Traditional loop
squares = []
for x in range(5):
    squares.append(x  2)

# List comprehension
squares = [x
2 for x in range(5)]
# Result: [0, 1, 4, 9, 16]

With Condition (Filtering):

# Only even numbers
evens = [x for x in range(10) if x % 2 == 0]
# Result: [0, 2, 4, 6, 8]

Transforming Lists:

names = ["alice", "bob", "charlie"]
upper_names = [name.upper() for name in names]
# Result: ["ALICE", "BOB", "CHARLIE"]

Syntax Pattern:

[expression for item in iterable if condition]
  • expression - What to do with each item
  • item - Variable for each element
  • iterable - The collection to loop over
  • condition - Optional filter

🎯 Your Challenge

Use a list comprehension to create a list called `doubled` that contains each number from 1 to 5 multiplied by 2. The result should be [2, 4, 6, 8, 10].

📝 Starter Code

Python
# Create doubled using list comprehension
# Should contain: [2, 4, 6, 8, 10]

doubled = 
  • List comprehensions use square brackets []
  • Put the expression (x * 2) first
  • Then write for x in range(...)
  • range(1, 6) gives numbers 1 to 5

Solution

Python
doubled = [x * 2 for x in range(1, 6)]

Explanation

We use range(1, 6) to generate numbers 1 through 5. For each number x, we multiply it by 2. The list comprehension creates the list in one concise line.

⚠️ Common Mistakes to Avoid

  • Using range(5) instead of range(1, 6)
  • Forgetting the square brackets
  • Wrong order of for and expression
  • Using append syntax inside comprehension

❓ Frequently Asked Questions

Yes, usually slightly faster because they are optimized internally by Python. They also use less memory when combined with generators.
Avoid them when the logic is complex or when you need multiple statements per iteration. Readability should come first.

🔗 Related Concepts