Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend/concatenate two iterators in Python [duplicate]

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?

like image 911
ywat Avatar asked May 22 '17 15:05

ywat


People also ask

How do you combine two iterators?

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.

How do you do two ranges in Python?

You can use itertools. chain for this: from itertools import chain concatenated = chain(range(30), range(2000, 5002)) for i in concatenated: ...

How do you concatenate lists in Python?

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.


1 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.

like image 128
Dan D. Avatar answered Sep 28 '22 02:09

Dan D.