0
0
Pythonprogramming~20 mins

Basic list comprehension syntax in Python - Practice Problems & Coding Challenges

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 simple list comprehension
What is the output of this Python code?
Python
result = [x * 2 for x in range(4)]
print(result)
A[0, 2, 4, 6]
B[1, 2, 3, 4]
C[2, 4, 6, 8]
D[0, 1, 2, 3]
Attempts:
2 left
๐Ÿ’ก Hint
Think about what range(4) produces and how each element is multiplied by 2.
โ“ Predict Output
intermediate
2:00remaining
List comprehension with condition
What is the output of this code?
Python
result = [x for x in range(6) if x % 2 == 0]
print(result)
A[1, 3, 5]
B[0, 1, 2, 3, 4, 5]
C[0, 2, 4]
D[2, 4, 6]
Attempts:
2 left
๐Ÿ’ก Hint
The condition filters numbers divisible by 2.
โ“ Predict Output
advanced
2:00remaining
Nested list comprehension output
What is the output of this nested list comprehension?
Python
result = [(x, y) for x in range(2) for y in range(3)]
print(result)
A[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
B[(0, 0), (1, 0), (0, 1), (1, 1), (0, 2), (1, 2)]
C[(0, 0), (1, 0), (2, 0), (0, 1), (1, 1), (2, 1)]
D[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]
Attempts:
2 left
๐Ÿ’ก Hint
The first loop is x, the second is y, so y changes faster.
โ“ Predict Output
advanced
2:00remaining
List comprehension with else clause (ternary)
What is the output of this code?
Python
result = [x if x % 2 == 0 else -x for x in range(5)]
print(result)
A[0, 1, 2, 3, 4]
B[0, -1, 2, -3, 4]
C[-0, 1, -2, 3, -4]
D[0, -1, -2, -3, -4]
Attempts:
2 left
๐Ÿ’ก Hint
If x is even, keep it; if odd, make it negative.
๐Ÿง  Conceptual
expert
2:00remaining
Understanding list comprehension order
Which option correctly describes the order in which elements are generated in this list comprehension?
result = [(x, y) for x in range(3) for y in range(2)]
AOnly pairs where x equals y are included.
BFor each y, all x values are paired before moving to the next y.
CPairs are generated randomly without order.
DFor each x, all y values are paired before moving to the next x.
Attempts:
2 left
๐Ÿ’ก Hint
Think about how nested loops work in Python.