8

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.

Community
  • 1
  • 1
zkurtz
  • 3,230
  • 7
  • 28
  • 64

3 Answers3

8

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

spalac24
  • 1,076
  • 1
  • 7
  • 16
3

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
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • looks promising, although I can't seem to get the `%timeit` parts to work. Some kind of syntax error. I tried importing `timeit` first, and that did not help. In general I don't follow your speed comparison. Are you saying that `numpy.fromiter` is the faster option? If so, is that the main reason for preferring it? – zkurtz Nov 11 '14 at 23:55
  • `%timeit` is part of [IPython shell](http://ipython.org/). Of course speed is one reason to prefer `.fromiter`, plus we don't have to create an intermediate list here. – Ashwini Chaudhary Nov 12 '14 at 05:33
1

You can do it with list(chain).

Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144
user3684792
  • 2,542
  • 2
  • 18
  • 23
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. – peterh Nov 11 '14 at 00:16
  • it doesn't answer the question '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]?' or the title statement 'Get a “plain old” array back from an itertools.chain object' – user3684792 Nov 11 '14 at 08:11