user3921265
user3921265

Reputation:

How can itertools.chain be used with a generator function?

In what follows, I am trying but failing in getting a flat list:

>>> from itertools import chain
>>> 
>>> def foo():
...     for i in range(3):
...         yield range(5)
... 
>>> 
>>> chain(foo)
<itertools.chain object at 0x7fce499934d0>
>>> 
>>> list(chain(foo()))
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
>>> 
>>> list(chain([foo()]))
[<generator object foo at 0x7fce49994aa0>]
>>> 
>>> list(chain(list(foo())))
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

What am I doing wrong? How can I get a flat list [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4] using itertools.chain?

Upvotes: 2

Views: 993

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117886

You're close, you can use chain.from_iterable from itertools

>>> list(itertools.chain.from_iterable(foo()))
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4]

Upvotes: 6

Related Questions