I want concatenate two iterators in an efficient way.
Suppose we have two iterators (in Python3)
l1 = range(10) # iterator over 0, 1, ..., 9 l2 = range(10, 20) # iterator over 10, 11, ..., 19
If we convert them to lists, it is easy to concatenate like
y = list(l1) + list(l2) # 0, 1, ,..., 19
However, this can be not efficient.
I would like to do something like
y_iter = l1 + l2 # this does not work
What is the good way to do this in Python3?
Merging Two Sorted Iterators in Java Then, we have to follow the remaining iterator and copy over the values. Unlike linked lists, for iterators, you have to iterate and copy over the values. With linked list, you can just re-point/re-connect the head with O(1) constant time.
You can use itertools. chain for this: from itertools import chain concatenated = chain(range(30), range(2000, 5002)) for i in concatenated: ...
Python's extend() method can be used to concatenate two lists in Python. The extend() function does iterate over the passed parameter and adds the item to the list thus, extending the list in a linear fashion. All the elements of the list2 get appended to list1 and thus the list1 gets updated and results as output.
Use itertools.chain
:
from itertools import chain y_iter = chain(l1, l2)
It yields all the items from l1
and then all the items from l2
. Effectively concatenating the sequence of yielded items. In the process it consumes both.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With