-1
[1.0, [1.0, [1.0, [0.25, [0.05, [0.01, [0.01, 0.01]]]]]]]

I am trying to flatten this list in python without using any modules not built into python 2. When I try to flatten it this error is raised:

 TypeError: 'float' object is not iterable on line 19
myang0630
  • 111
  • 5
  • possibly: https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists – 7 Reeds Jan 15 '20 at 20:49
  • Tried that- didn't work. Apparently floats are different and also I'm using Python 2. This question is not a duplicate... I have seen that thread and the method used there does not work for me. – myang0630 Jan 15 '20 at 20:50

1 Answers1

2

You can use recursion to flatten nested list:

def flatten(lst):
    for i in lst:
        if isinstance(i, list):
            for v in flatten(i):
                yield v
        else:
            yield i

lst = [1.0, [1.0, [1.0, [0.25, [0.05, [0.01, [0.01, 0.01]]]]]]]

lst = list(flatten(lst))
print(lst)

Prints:

[1.0, 1.0, 1.0, 0.25, 0.05, 0.01, 0.01, 0.01]
Andrej Kesely
  • 118,151
  • 13
  • 38
  • 75