1

I have a nested list to flatten:

L = [[1, 0, 0], 23, 30, [1, 1, 0], [1, 1]]

I used two approaches but none of them worked:

First:

flattened_list = []

for x in L:
    for y in x:
        flattened_list.append(y)

Error:

'int' object is not iterable

Second (list comprehension):

[y for x in L for y in x]

Error:

'int' object is not iterable

UPDATE This question is somewhat different because 23 and 30 are not in lists. If I do

L = [[1, 0, 0], [23], [30], [1, 1, 0], [1, 1]]

Then the following works:

merged = list(itertools.chain(*L))

[1, 0, 0, 23, 30, 1, 1, 0, 1, 1]
yearntolearn
  • 1,064
  • 2
  • 17
  • 36
  • 1
    *What did I do wrong?* you tried to loop through the elements of an integer, but integers are scalars and don't have elements through which you can loop. Before your second `for` loop, you should test if the current element (`x`) is an iterable. If it's not, the second loop should be bypassed. – Paul H Jul 29 '16 at 17:36

0 Answers0