Python Programming - Generators
Exercise : Generators - General Questions
- Generators - General Questions
86.
How does the
itertools.compress()
function differ from itertools.filterfalse()
when used with generators?
Answer: Option
Explanation:
itertools.compress()
filters elements from the data iterable based on corresponding truth values in the selectors iterable. itertools.filterfalse()
filters elements based on a false condition.
87.
How does the
generator.throw(StopIteration)
method differ from raise StopIteration
when used with a generator?
Answer: Option
Explanation:
generator.throw(StopIteration)
is used to raise a StopIteration
exception inside the generator, while raise StopIteration
is used outside the generator to signal the end of iteration.
88.
How does the
itertools.zip_longest()
function differ from zip()
when used with generators?
Answer: Option
Explanation:
itertools.zip_longest()
continues until the longest iterable is exhausted, filling in missing values with a specified fillvalue. zip()
stops when the shortest iterable is exhausted.
import itertools
gen1 = (1, 2, 3)
gen2 = ('a', 'b')
zipped_iterable = itertools.zip_longest(gen1, gen2, fillvalue=None)
regular_zip = zip(gen1, gen2)
print(list(zipped_iterable)) # Output: [(1, 'a'), (2, 'b'), (3, None)]
print(list(regular_zip)) # Output: [(1, 'a'), (2, 'b')]
89.
How does the
itertools.islice()
function differ from using slice()
with a generator?
Answer: Option
Explanation:
itertools.islice()
is specifically designed for slicing iterables, including generators. slice()
is used for indexing sequences, not for creating a sliced iterable.
90.
What is the purpose of the
itertools.accumulate()
function when used with generators?
Answer: Option
Explanation:
itertools.accumulate()
applies a specified function cumulatively to the elements of a generator, yielding the intermediate results.
import itertools
gen = (1, 2, 3, 4)
accumulated_iterable = itertools.accumulate(gen, lambda x, y: x + y)
print(list(accumulated_iterable)) # Output: [1, 3, 6, 10]
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers