Using the itertools.tee() function to duplicate iterators
itertools.tee()
is an interesting function from the itertools module that allows you to create multiple independent copies of the same iterator.
🗣️ This is useful when you need to iterate over the same data in different parts of the code simultaneously, without repeating calculations.
✔️ itertools.tee()
makes working with iterators more flexible and convenient.
from itertools import tee
# Create an iterator
numbers = iter([1, 2, 3, 4, 5])
# Create two independent copies of the iterator
numbers1, numbers2 = tee(numbers, 2)
print(list(numbers1))
print(list(numbers2))
# [1, 2, 3, 4, 5]
# [1, 2, 3, 4, 5]
# Execution result:
# [1, 2, 3, 4, 5]
# [1, 2, 3, 4, 5]
Page of .
Leave a comment
You must be logged in to leave a comment.
Log in or
sign up to join the discussion.
Comments (0)