Python List Comprehensions and Generators Flashcards
6 cards from real Python practice questions. Tap to flip, then mark Knew It or Still Learning โ missed cards come back until you master them.
Read the first 6 Python List Comprehensions and Generators flashcards as text
What does `next()` do when called on a generator that is exhausted?
Answer: Raises a StopIteration exception
Once a generator has no more values to yield, calling next() raises StopIteration.
What is the result of `[i*j for i in range(1,3) for j in range(1,3)]`?
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.
Which built-in function can be used to create an iterator from any iterable?
Answer: iter()
iter() returns an iterator object from any iterable, calling its __iter__ method.
What does `yield from` do in a generator function?
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.
What is the output of `[x for x in [1,2,3,4,5] if x > 3]`?
Answer: [4, 5]
The filter condition x > 3 keeps only 4 and 5 from the original list.
Which of the following is a valid dict comprehension?
Answer: {k: v for k, v in items}
A dict comprehension uses curly braces with a key:value expression followed by for clauses.