Python Python List Comprehensions and Generators 2 — Questions and Answers
Question 1: What does `next()` do when called on a generator that is exhausted?
- Returns None
- Restarts the generator from the beginning
- Raises a StopIteration exception (Correct answer)
- Returns the last yielded value
Correct answer: Raises a StopIteration exception
Once a generator has no more values to yield, calling next() raises StopIteration.
Question 2: What is the result of `[i*j for i in range(1,3) for j in range(1,3)]`?
- [1, 2, 2, 4] (Correct answer)
- [1, 4]
- [1, 2, 3, 4]
- [2, 4]
Correct answer: [1, 2, 2, 4]
The nested comprehension iterates i over [1,2] and j over [1,2], producing 1*1=1, 1*2=2, 2*1=2, 2*2=4.
Question 3: Which built-in function can be used to create an iterator from any iterable?
- next()
- iter() (Correct answer)
- enumerate()
- zip()
Correct answer: iter()
iter() returns an iterator object from any iterable, calling its __iter__ method.
Question 4: What does `yield from` do in a generator function?
- Creates a new generator function
- Delegates to a sub-generator, yielding all its values (Correct answer)
- Returns all values at once as a list
- Raises StopIteration immediately
Correct answer: Delegates to a sub-generator, yielding all its values
yield from sub_gen delegates to a sub-generator, yielding each of its values as if they were in the outer generator.
Question 5: What is the output of `[x for x in [1,2,3,4,5] if x > 3]`?
- [1, 2, 3]
- [4, 5] (Correct answer)
- [3, 4, 5]
- [1, 2]
Correct answer: [4, 5]
The filter condition x > 3 keeps only 4 and 5 from the original list.
Question 6: Which of the following is a valid dict comprehension?
- {k: v for k, v in items} (Correct answer)
- [k:v for k,v in items]
- (k: v for k, v in items)
- dict[k: v for k, v in items]
Correct answer: {k: v for k, v in items}
A dict comprehension uses curly braces with a key:value expression followed by for clauses.
What does `next()` do when called on a generator that is exhausted?