Challenge - 5 Problems
List Comprehension Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of list comprehension vs loop
What is the output of the following code snippet?
Python
result = [] for i in range(3): result.append(i * 2) print(result)
Attempts:
2 left
๐ก Hint
Think about what happens when you multiply each number in the range by 2.
โ Incorrect
The loop multiplies each number 0,1,2 by 2 and appends it to the list, resulting in [0, 2, 4].
โ Predict Output
intermediate2:00remaining
Equivalent list comprehension output
Which option shows the output of this list comprehension?
result = [x**2 for x in range(4)] print(result)
Attempts:
2 left
๐ก Hint
Remember that x**2 means x squared.
โ Incorrect
The list comprehension squares each number from 0 to 3, resulting in [0, 1, 4, 9].
โ Predict Output
advanced2:00remaining
Output difference between loop and list comprehension with condition
What is the output of this code?
result = []
for x in range(5):
if x % 2 == 0:
result.append(x + 1)
print(result)Attempts:
2 left
๐ก Hint
Check which numbers are even and what happens when you add 1.
โ Incorrect
Only even numbers 0,2,4 are selected and 1 is added to each, resulting in [1, 3, 5].
โ Predict Output
advanced2:00remaining
List comprehension with condition output
What is the output of this list comprehension?
result = [x + 1 for x in range(5) if x % 2 == 0] print(result)
Attempts:
2 left
๐ก Hint
The condition filters even numbers, then adds 1 to each.
โ Incorrect
The list comprehension selects even numbers 0,2,4 and adds 1, resulting in [1, 3, 5].
โ Predict Output
expert2:00remaining
Comparing performance: loop vs list comprehension
Which option correctly describes the output of this timing code?
import time
start = time.time()
result = []
for i in range(1000000):
result.append(i)
end = time.time()
print(round(end - start, 2))
and
start = time.time() result = [i for i in range(1000000)] end = time.time() print(round(end - start, 2))
Attempts:
2 left
๐ก Hint
Think about how Python optimizes list comprehensions.
โ Incorrect
List comprehensions are optimized in Python and usually run faster than equivalent loops.