Python Programming - Generators
Exercise : Generators - General Questions
- Generators - General Questions
81.
What happens if a generator function contains a
return
statement followed by a yield
statement?
Answer: Option
Explanation:
If a generator function contains both
return
and yield
statements, it returns the specified value and stops the generator.
def my_generator():
return 42
yield # This statement is never reached
# Example usage
gen = my_generator()
result = next(gen, None)
print(result) # Output: 42
82.
How does the
itertools.cycle()
function differ from using itertools.repeat()
with a specified count when used with generators?
Answer: Option
Explanation:
itertools.cycle()
repeats the elements of a generator indefinitely, while itertools.repeat()
stops after a specified count.
import itertools
gen = (1, 2, 3)
cycle_iterable = itertools.cycle(gen)
repeat_iterable = itertools.repeat(gen, times=3)
print(list(itertools.islice(cycle_iterable, 10))) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3, 1]
print(list(repeat_iterable)) # Output: [(1, 2, 3), (1, 2, 3), (1, 2, 3)]
83.
How does the
itertools.groupby()
function differ from collections.Counter()
when used with generators?
Answer: Option
Explanation:
itertools.groupby()
groups consecutive elements based on a key function, creating subgroups. collections.Counter()
counts the occurrences of each element in the entire iterable.
84.
What is the purpose of the
generator.send(value)
method when used with generators?
Answer: Option
Explanation:
generator.send(value)
sends a value into the generator, which is received as the result of the current yield
expression, and resumes the generator's execution.
def my_generator():
result = yield
print(f"Received value: {result}")
gen = my_generator()
next(gen) # Start the generator
gen.send(42) # Output: Received value: 42
85.
How does the
itertools.dropwhile()
function differ from itertools.filterfalse()
when used with generators?
Answer: Option
Explanation:
itertools.dropwhile()
skips elements until a specified condition becomes false, while itertools.filterfalse()
filters elements based on a false condition.
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers