0
0
Pythonprogramming~20 mins

Why list comprehension is used in Python - Challenge Your Understanding

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!
๐Ÿง  Conceptual
intermediate
2:00remaining
Why use list comprehension instead of a for loop?

Which of the following is the main reason programmers use list comprehensions in Python?

AThey allow you to create dictionaries instead of lists.
BThey make the code shorter and easier to read.
CThey always run faster than any other code.
DThey prevent errors by automatically checking data types.
Attempts:
2 left
๐Ÿ’ก Hint

Think about how list comprehensions change the way you write loops.

โ“ Predict Output
intermediate
2:00remaining
Output of list comprehension creating squares

What is the output of this Python code?

Python
squares = [x*x for x in range(5)]
print(squares)
A[0, 1, 4, 9, 16]
B[1, 4, 9, 16, 25]
C[0, 1, 2, 3, 4]
D[1, 2, 3, 4, 5]
Attempts:
2 left
๐Ÿ’ก Hint

Remember that range(5) gives numbers from 0 to 4.

โ“ Predict Output
advanced
2:00remaining
Filtering with list comprehension output

What will this code print?

Python
evens = [x for x in range(10) if x % 2 == 0]
print(evens)
A[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
B[1, 3, 5, 7, 9]
C[0, 2, 4, 6, 8]
D[]
Attempts:
2 left
๐Ÿ’ก Hint

Look at the condition x % 2 == 0 inside the list comprehension.

๐Ÿง  Conceptual
advanced
2:00remaining
Why list comprehension is preferred for creating lists?

Which statement best explains why list comprehensions are preferred for creating lists in Python?

AThey allow combining loops and conditions in a single, readable line.
BThey replace the need for functions in Python.
CThey can only be used with numbers, making code safer.
DThey automatically optimize memory usage better than loops.
Attempts:
2 left
๐Ÿ’ก Hint

Think about how list comprehensions combine multiple steps.

โ“ Predict Output
expert
2:00remaining
Output of nested list comprehension

What is the output of this nested list comprehension?

Python
matrix = [[i*j for j in range(3)] for i in range(3)]
print(matrix)
A[[0, 0, 0], [0, 1, 2], [0, 2, 6]]
B[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
C[[0, 0, 0], [1, 1, 1], [2, 2, 2]]
D[[0, 0, 0], [0, 1, 2], [0, 2, 4]]
Attempts:
2 left
๐Ÿ’ก Hint

Calculate each element as i * j for i and j from 0 to 2.