Ask Your Question
2

How can iterators be chained in Python without modifying the original instance?

asked 2023-06-29 23:57:43 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-06-30 00:24:02 +0000

pufferfish gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-29 23:57:43 +0000

Seen: 12 times

Last updated: Jun 30 '23