1

I have an array of array in python. What is the best way to convert it to an array in python? for example:

m = [[1,2],[3,4]]
# convert to [1,2,3,4]

I am new in python, so I dont know any solution of it better than writing a loop. Please help.

Moazzam Khan
  • 3,130
  • 2
  • 20
  • 35
  • 3
    This is called flattening a nested list. These keywords should help in your research. – Lev Levitsky Feb 12 '13 at 12:53
  • 1
    First thing you should do is get in terms with the python terminology. It will make it easier for you to look for code samples and ask questions. There are no arrays in python (unless you use some 3rd paty module such as numpy), there are lists. – StoryTeller - Unslander Monica Feb 12 '13 at 12:56
  • @StoryTeller: There are in fact no built-in arrays in Python. However, arrays are available through the standard array module (http://docs.python.org/2/library/array.html). – Eric O. Lebigot Feb 12 '13 at 13:14
  • The type you are using are not arrays but lists. As said by EOL, *arrays are available through the [standard array](http://docs.python.org/2/library/array.html) module* – pradyunsg Feb 12 '13 at 13:28

1 Answers1

5

Use itertools.chain or list comprehension:

from itertools import chain

list(chain(*m))  # shortest
# or:
list(chain.from_iterable(m)) # more efficient  

For smaller lists comprehension is faster, for longer ones chain.from_iterable is more suitable.

[item for subl in m for item in subl]

For understanding the nested comprehension, you can split it across multiple lines and compare it to a regular for loop:

[item                         #result = []
    for subl in m             #for subl in m:  
        for item in subl]     #    for item in subl:
                              #        result.append(item)
root
  • 76,608
  • 25
  • 108
  • 120