zkurtz
zkurtz

Reputation: 3288

Get an array back from an itertools.chain object

Suppose I have list_of_numbers = [[1, 2], [3], []] and I want the much simpler object list object x = [1, 2, 3].

Following the logic of this related solution, I do

list_of_numbers = [[1, 2], [3], []]
import itertools
chain = itertools.chain(*list_of_numbers)

Unfortunately, chain is not exactly what I want because (for instance) running chain at the console returns <itertools.chain object at 0x7fb535e17790>.

What is the function f such that if I do x = f(chain) and then type x at the console I get [1, 2, 3]?

Update: Actually the result I ultimately need is array([1, 2, 3]). I'm adding a line in a comment on the selected answer to address this.

Upvotes: 8

Views: 13179

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250961

If your ultimate goal is to get a Numpy array then you should use numpy.fromiter here:

>>> import numpy as np
>>> from itertools import chain
>>> list_of_numbers = [[1, 2], [3], []]
>>> np.fromiter(chain(*list_of_numbers), dtype=int)
array([1, 2, 3])
>>> list_of_numbers = [[1, 2]*1000, [3]*1000, []]*1000
>>> %timeit np.fromiter(chain(*list_of_numbers), dtype=int)
10 loops, best of 3: 103 ms per loop
>>> %timeit np.array(list(chain(*list_of_numbers)))
1 loops, best of 3: 199 ms per loop

Upvotes: 3

user3684792
user3684792

Reputation: 2611

You can do it with list(chain).

Upvotes: 1

spalac24
spalac24

Reputation: 1116

list. If you do list(chain) it should work. But use this just for debugging purposes, it could be inefficient in general.

Upvotes: 8

Related Questions