0

I was trying to "flatten" an array, to convert it to 1 single dimension set of items. I work with the append command and I get this:

[['X', 'X'],['ff','ff','ff','ff','ff']]

But I would prefer to have the elements sorted as:

['X','X','ff','ff','ff','ff','ff']

I cannot use the string.join() or string.split() operators. So which is the most sensible way to perform this action?

Ramon Blanquer
  • 392
  • 3
  • 8
  • 22
  • Part of the point of this site is to serve as a repository for solutions to common problems. Your problem is an extremely common one, and has been asked many, many times here already. Use the search box near the upper right corner to look for "python flatten" and you'll get lots of hits. [Here](http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python) is one in particular which, right at the very top, acknowledges and links to earlier Stack Overflow questions. – John Y Mar 21 '14 at 16:39

4 Answers4

4

I think what you're looking for is extend() rather than append()

>>> oldList = [['X', 'X'],['ff','ff','ff','ff','ff']]
>>> print oldList
[['X', 'X'], ['ff', 'ff', 'ff', 'ff', 'ff']]
>>> newList = []
>>> for item in oldList:
...     newList.extend( item )
>>> print newList
>>> ['X', 'X', 'ff', 'ff', 'ff', 'ff', 'ff']
user3033893
  • 900
  • 11
  • 11
3

Using list comprehension:

alist = [['X', 'X'],['ff','ff','ff','ff','ff']]
print [j for i in alist for j in i ]

Using reduce:

reduce(lambda r,x:r+x, alist,[])

Output:

['X', 'X', 'ff', 'ff', 'ff', 'ff', 'ff']
venpa
  • 4,268
  • 21
  • 23
  • 2
    According to [this post](http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python), the list comprehension is considerably faster than `reduce(lambda...)` – wflynny Mar 21 '14 at 16:40
2

Use itertools.chain or extend()

>>> from itertools import chain
>>> oldList = [['X', 'X'],['ff','ff','ff','ff','ff']]
>>> list(chain.from_iterable(oldList))
['X', 'X', 'ff', 'ff', 'ff', 'ff', 'ff']

>>> list1 = ['X', 'X']
>>> list1.extend(['ff','ff','ff','ff','ff'])
>>> list1
['X', 'X', 'ff', 'ff', 'ff', 'ff', 'ff']
Hashmush
  • 1,973
  • 2
  • 11
  • 12
  • 1
    `chain.from_iterable(oldList)` is preferred to `chain(*oldList)` as the latter will resolve the iterable into a `tuple` first. – mgilson Mar 21 '14 at 16:42
1

For the sake of completeness, there is always

In [1]: x = [['X', 'X'], ['ff', 'ff', 'ff', 'ff', 'ff']]
In [2]: sum(x, [])
Out[2]: ['X', 'X', 'ff', 'ff', 'ff', 'ff', 'ff']

but

In [3]: [item for sublist in x for item in sublist]
Out[3]: ['X', 'X', 'ff', 'ff', 'ff', 'ff', 'ff']

should be faster, and

In [4]: from itertools import chain
In [5]: list(chain.from_iterable(x))
Out[5]: ['X', 'X', 'ff', 'ff', 'ff', 'ff', 'ff']

should be fastest.

wflynny
  • 18,065
  • 5
  • 46
  • 67