Python Python List Comprehensions and Generators 1 — Questions and Answers
Question 1: What is the output of `[x**2 for x in range(4)]`?
- [0, 1, 4, 9] (Correct answer)
- [1, 4, 9, 16]
- [0, 1, 2, 3]
- [1, 2, 3, 4]
Correct answer: [0, 1, 4, 9]
range(4) produces 0, 1, 2, 3, and squaring each gives [0, 1, 4, 9].
Question 2: Which syntax creates a generator expression in Python?
- [x for x in range(10)]
- (x for x in range(10)) (Correct answer)
- {x for x in range(10)}
- generator(x for x in range(10))
Correct answer: (x for x in range(10))
Parentheses around a comprehension-style expression create a generator, not a list.
Question 3: What does the `yield` keyword do in a Python function?
- Returns a value and terminates the function
- Pauses execution and returns a value to the caller, resuming on next call (Correct answer)
- Raises a StopIteration exception
- Creates a new thread
Correct answer: Pauses execution and returns a value to the caller, resuming on next call
yield turns a function into a generator, pausing at each yield and resuming from that point when next() is called.
Question 4: What is the output of `list(x for x in range(5) if x % 2 == 0)`?
- [1, 3]
- [0, 2, 4] (Correct answer)
- [0, 1, 2, 3, 4]
- [2, 4]
Correct answer: [0, 2, 4]
The condition x % 2 == 0 filters to even numbers 0, 2, and 4 from range(5).
Question 5: Which of the following creates a set comprehension?
- [x*2 for x in range(5)]
- (x*2 for x in range(5))
- {x*2 for x in range(5)} (Correct answer)
- set(x*2 for x in range(5) using {})
Correct answer: {x*2 for x in range(5)}
Curly braces with a single expression and no colon create a set comprehension.
Question 6: What is the memory advantage of using a generator over a list?
- Generators store all values in memory upfront
- Generators produce values one at a time, using constant memory (Correct answer)
- Generators are faster for random access
- Generators support indexing like lists
Correct answer: Generators produce values one at a time, using constant memory
Generators yield values lazily one at a time, so they never hold the entire sequence in memory.
What is the output of `[x**2 for x in range(4)]`?