Python Programming - Generators

Exercise : Generators - General Questions
  • Generators - General Questions
96.
How does the itertools.tee() function behave when used with a generator that contains mutable objects?
It raises a TypeError
It creates independent iterators, and changes in one iterator affect the others
It creates independent iterators, and changes in one iterator do not affect the others
It raises a ValueError
Answer: Option
Explanation:
itertools.tee() creates independent iterators, and changes in one iterator do not affect the others. Each iterator maintains its own state.
import itertools

def generator_with_mutable():
    mutable_list = [1, 2, 3]
    for item in mutable_list:
        yield item

gen1, gen2 = itertools.tee(generator_with_mutable(), 2)

# Modify gen1 without affecting gen2
next(gen1)          
gen1_list = list(gen1)
gen2_list = list(gen2)

print(gen1_list)   # Output: [2, 3]
print(gen2_list)   # Output: [1, 2, 3]

97.
How does the itertools.count() function behave when used with a specified step value?
It raises a TypeError
It creates an infinite sequence of integers with the specified step value
It stops after reaching the specified step value
It raises a ValueError
Answer: Option
Explanation:
itertools.count() creates an infinite sequence of integers, and if a step value is specified, it increments each subsequent element by that step value.
import itertools

count_by_twos = itertools.count(start=0, step=2)

result = [next(count_by_twos) for _ in range(5)]
print(result)  # Output: [0, 2, 4, 6, 8]

98.
How does the itertools.zip_longest() function behave when used with generators of unequal lengths?
It raises a TypeError
It stops when the shortest generator is exhausted
It raises a ValueError
It continues until the longest generator is exhausted, filling in missing values with a specified fillvalue
Answer: Option
Explanation:
itertools.zip_longest() continues until the longest iterable is exhausted, filling in missing values with a specified fillvalue.
import itertools

gen1 = (1, 2, 3)
gen2 = ('a', 'b')

zipped_iterable = itertools.zip_longest(gen1, gen2, fillvalue=None)

print(list(zipped_iterable))  # Output: [(1, 'a'), (2, 'b'), (3, None)]

99.
What does the yield from statement do when used in a generator?
It yields a single value from the generator
It raises a TypeError
It delegates part of the generator's operation to another generator or iterable
It stops the generator and raises a StopIteration exception
Answer: Option
Explanation:
yield from is used to delegate part of the generator's operation to another generator or iterable. It simplifies the syntax for generators that yield from another iterable.
def generator_delegator():
    yield from range(3)
    yield from 'abc'

result = list(generator_delegator())
print(result)  # Output: [0, 1, 2, 'a', 'b', 'c']