How to extend/concatenate two iterators in Python
Question:
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?
Answers:
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.
you can use the chain() function provided by the itertools
itertools.chain()
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?
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.
you can use the chain() function provided by the itertools
itertools.chain()