Converting matrix to an array in python

Question:

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.

Asked By: Moazzam Khan

||

Answers:

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)
Answered By: root
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.