Python Programming - Generators
Exercise : Generators - General Questions
- Generators - General Questions
36.
How does the
generator.throw(StopIteration)
method affect a running generator?
Answer: Option
Explanation:
generator.throw(StopIteration)
forcibly terminates the running generator by raising a StopIteration
exception.
37.
How does the
itertools.filterfalse()
function behave when used with a generator?
Answer: Option
Explanation:
itertools.filterfalse()
filters elements in the generator that evaluate to False
based on the provided function.
38.
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)}")
39.
How does the
generator.__iter__()
method differ from the iter()
built-in function when applied to a generator?
Answer: Option
Explanation:
generator.__iter__()
returns the generator itself, treating the generator as its own iterator. iter()
returns a new iterator object for the generator.
def my_generator():
yield 1
yield 2
yield 3
# Using generator.__iter__()
gen_iter = my_generator().__iter__()
print(next(gen_iter)) # Output: 1
# Using iter()
iter_obj = iter(my_generator())
print(next(iter_obj)) # Output: 1
40.
What is the purpose of the
itertools.islice()
function when used with generators?
Answer: Option
Explanation:
itertools.islice()
is used to slice a generator into specified ranges, allowing you to extract a portion of the generator's elements without consuming the entire sequence.
import itertools
def my_generator():
for i in range(10):
yield i
# Using itertools.islice() to slice the generator
sliced_generator = itertools.islice(my_generator(), 2, 7)
for value in sliced_generator:
print(value)
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers