Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Iterators in Python can be chained using the itertools.chain() function. The chain() function returns a new iterator that iterates over all the items in the input iterators in the order they are passed, without modifying the original instances.

Here's an example of how to chain two iterators:

import itertools

iter1 = iter([1, 2, 3])
iter2 = iter([4, 5, 6])

chained_iter = itertools.chain(iter1, iter2)

for num in chained_iter:
    print(num)

Output:

1
2
3
4
5
6

In this example, we first create two separate iterators iter1 and iter2. Then, we call the chain() function on these iterators to create a new iterator chained_iter that iterates over all the elements of iter1 and iter2 in sequence. Finally, we iterate over chained_iter using a for loop to print all the numbers.