Python Programming - Generators
Exercise : Generators - General Questions
- Generators - General Questions
61.
How does the
generator.throw(StopIteration)
method affect a running generator?
Answer: Option
Explanation:
generator.throw(StopIteration)
stops the generator and raises a StopIteration
exception. However, using raise StopIteration
directly is preferred.
def my_generator():
try:
while True:
yield 1
except StopIteration:
print("Generator stopped")
gen = my_generator()
next(gen)
gen.throw(StopIteration)
62.
What happens if the
generator.throw(ValueError, "message")
method is called with a non-existent exception type?
Answer: Option
Explanation:
If the specified exception type does not exist,
generator.throw()
has no effect on the running generator.
63.
What is the purpose of the
itertools.groupby()
function when used with generators?
Answer: Option
Explanation:
itertools.groupby()
groups consecutive equal elements from the generator based on a key function.
import itertools
def my_generator():
yield 1
yield 1
yield 2
yield 3
yield 3
grouped_generator = itertools.groupby(my_generator())
for key, group in grouped_generator:
print(f"Key: {key}, Group: {list(group)}")
64.
How does the
itertools.zip_longest()
function differ from zip()
when used with generators?
Answer: Option
Explanation:
itertools.zip_longest()
fills in missing values with None
for the shorter iterables, while zip()
stops when the shortest iterable is exhausted.
import itertools
gen1 = (1, 2, 3)
gen2 = ('a', 'b')
zipped = zip(gen1, gen2)
zip_longest = itertools.zip_longest(gen1, gen2)
print(list(zipped)) # Output: [(1, 'a'), (2, 'b')]
print(list(zip_longest)) # Output: [(1, 'a'), (2, 'b'), (3, None)]
65.
How does the
itertools.filterfalse()
function differ from filter()
when used with generators?
Answer: Option
Explanation:
itertools.filterfalse()
filters elements from the generator for which the filtering function returns false, while filter()
filters based on a true condition.
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers