Flattening a nested list structure with integers in Python? This code not respond to the usual attempts to tweak it as per the other post

Viewed 13

Ok so I am trying to flatten the given nested list structure to go from the original list to the flattened list. I have tried a variety of codes which I will show below but just received errors or similar.

Flatten a given nested list structure.

Original list: [0, 10, [20, 30], 40, 50, [60, 70, 80], [90, 100, 110, 120]]

Flatten list: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120] (This is what my output needs to be)

So I tried this code

flat_list = [i for num in a for i in num] print(flat_list)

Output: TypeError: 'int' object is not iterable

Then I tried this code

flattened = []

for num in a: for i in a: flattened.append(i)

print(flattened)

Output: [0, 10, [20, 30], 40, 50, [60, 70, 80], [90, 100, 110, 120], 0, 10, [20, 30], 40, 50, [60, 70, 80], [90, 100, 110, 120], 0, 10, [20, 30], 40, 50, [60, 70, 80], [90, 100, 110, 120], 0, 10, [20, 30], 40, 50, [60, 70, 80], [90, 100, 110, 120], 0, 10, [20, 30], 40, 50, [60, 70, 80], [90, 100, 110, 120], 0, 10, [20, 30], 40, 50, [60, 70, 80], [90, 100, 110, 120], 0, 10, [20, 30], 40, 50, [60, 70, 80], [90, 100, 110, 120]]

I am not sure what I am doing wrong because I either get an error or just the list repeating no matter how much I manipulate the code. How can I tweak my code to get the desired output?

0 Answers
Related