Python Programming - Generators - Discussion

Discussion Forum : Generators - General Questions (Q.No. 96)
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]
Discussion:
Be the first person to comment on this question !

Post your comments here:

Your comments will be displayed after verification.