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.
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.
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)