0

I'm a pretty sure that this is a silly question, but I can't wrap my head around what is wrong.

I have a list of lists and I'd like to use list comprehension to create a single list holding all elements (like a flattened list).

What I have tried so far:

lol = [[0,1,2,3], [4,5,6,7], [8,9,10,11]]
fl = [el for el in al for al in lol]

But then I get NameError: name 'al' is not defined.

Is this just not doable in list-comprehension or am I doing something wrong?

LeKnecht
  • 25
  • 2
  • 2
    The ordering of the `for` loops follows that of regular `for` loops. Start from the outside and work inwards – roganjosh Mar 22 '19 at 10:39

2 Answers2

3

You Fix:

print([el for al in lol for el in al])

Using list comprehension (for better understanding):

lol = [[0,1,2,3], [4,5,6,7], [8,9,10,11]]
print([item for sublist in lol for item in sublist])

OUTPUT:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

EDIT (for readability):

flattened = []
for sublist in lol:
    for item in sublist:
        flattened.append(item)

print(flattened)

OUTPUT:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

Using reduce:

from functools import reduce
print(reduce(lambda x, y: x + y, lol))

EDIT 2:

While I was at it, here is another cooler way using deepflatten:

from iteration_utilities import deepflatten       
print(list(deepflatten(lol, depth=1)))

EDIT 3:

Using numpy:

import numpy as np
print (np.concatenate(lol))

You could just concatenate() the lists but with a warning that it wont work with single dimensional arrays.

DirtyBit
  • 15,671
  • 4
  • 26
  • 53
0

You are almost right! However the for-clauses need inversion:

fl = [el for al in lol for el in al]