0
0
Pythonprogramming~20 mins

List comprehension vs loop in Python - Practice Questions

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
List Comprehension Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2: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)
A[0, 2, 4]
B[0, 1, 2]
C[2, 4, 6]
D[0, 4, 8]
Attempts:
2 left
๐Ÿ’ก Hint
Think about what happens when you multiply each number in the range by 2.
โ“ Predict Output
intermediate
2:00remaining
Equivalent list comprehension output
Which option shows the output of this list comprehension?
result = [x**2 for x in range(4)]
print(result)
A[1, 4, 9, 16]
B[0, 1, 4, 9]
C[0, 2, 4, 6]
D[1, 2, 3, 4]
Attempts:
2 left
๐Ÿ’ก Hint
Remember that x**2 means x squared.
โ“ Predict Output
advanced
2: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)
A[0, 2, 4]
B[1, 2, 3, 4, 5]
C[1, 3, 5]
D[2, 4, 6]
Attempts:
2 left
๐Ÿ’ก Hint
Check which numbers are even and what happens when you add 1.
โ“ Predict Output
advanced
2: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)
A[1, 3, 5]
B[2, 4, 6]
C[0, 2, 4]
D[1, 2, 3, 4, 5]
Attempts:
2 left
๐Ÿ’ก Hint
The condition filters even numbers, then adds 1 to each.
โ“ Predict Output
expert
2: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))
ABoth take exactly the same time.
BLoop is faster than list comprehension.
CBoth raise a runtime error due to memory.
DList comprehension is generally faster than the loop.
Attempts:
2 left
๐Ÿ’ก Hint
Think about how Python optimizes list comprehensions.