Which of the following is the main reason programmers use list comprehensions in Python?
Think about how list comprehensions change the way you write loops.
List comprehensions help write loops in a shorter and clearer way, making code easier to understand and maintain.
What is the output of this Python code?
squares = [x*x for x in range(5)] print(squares)
Remember that range(5) gives numbers from 0 to 4.
The list comprehension squares each number from 0 to 4, resulting in [0, 1, 4, 9, 16].
What will this code print?
evens = [x for x in range(10) if x % 2 == 0] print(evens)
Look at the condition x % 2 == 0 inside the list comprehension.
The code selects only even numbers from 0 to 9, so the list is [0, 2, 4, 6, 8].
Which statement best explains why list comprehensions are preferred for creating lists in Python?
Think about how list comprehensions combine multiple steps.
List comprehensions let you write loops and conditions together in one line, making code cleaner and easier to understand.
What is the output of this nested list comprehension?
matrix = [[i*j for j in range(3)] for i in range(3)] print(matrix)
Calculate each element as i * j for i and j from 0 to 2.
The nested list comprehension creates a 3x3 matrix where each element is the product of its row and column indices.