Recall & Review
beginner
What is a list comprehension in Python?
A list comprehension is a concise way to create lists by writing a single expression inside square brackets. It combines a loop and an optional condition in one line.
Click to reveal answer
beginner
How does a for loop differ from a list comprehension?
A for loop executes multiple statements over iterations and builds a list step-by-step, often requiring more lines. A list comprehension creates the list in one compact expression.
Click to reveal answer
intermediate
Which is generally faster: list comprehension or a for loop?
List comprehensions are usually faster because they are optimized internally in Python, reducing overhead compared to explicit for loops.
Click to reveal answer
beginner
Can list comprehensions include conditions?
Yes, list comprehensions can include conditions to filter items. For example: [x for x in range(10) if x % 2 == 0] creates a list of even numbers.
Click to reveal answer
intermediate
When might you prefer a for loop over a list comprehension?
Use a for loop when you need to perform multiple actions inside the loop or when the logic is too complex to fit clearly in a single expression.
Click to reveal answer
Which syntax creates a list of squares from 0 to 4 using list comprehension?
✗ Incorrect
Option B correctly uses list comprehension syntax to create a list of squares.
What is a key advantage of list comprehensions over for loops?
✗ Incorrect
List comprehensions are concise and usually faster due to internal optimizations.
Which of these is NOT a valid list comprehension?
✗ Incorrect
Option D has incorrect syntax; the 'for' must come after the opening bracket.
When is a for loop preferred over a list comprehension?
✗ Incorrect
For loops allow multiple statements and complex logic inside the loop.
What does this list comprehension do? [x for x in range(5) if x > 2]
✗ Incorrect
It filters numbers greater than 2, so the list is [3, 4].
Explain the main differences between list comprehensions and for loops in Python.
Think about code length, speed, and complexity.
You got /4 concepts.
Describe a situation where you would choose a for loop instead of a list comprehension.
Consider when one line is not enough.
You got /3 concepts.