I
I
Igor Statkevich2018-10-31 11:43:43
Python
Igor Statkevich, 2018-10-31 11:43:43

How to iterate over nested lists of indeterminate depth?

Let's say there is a list [1, 2, [3, 4, 5, [6, 7],[8, [9, [10, 11], 12]]], 13, 14]],15]
there is a list with nested lists of indeterminate depth, it is necessary to go through each element and output in the right order
1,
2,
3
...
15
recursion is necessary or I don’t even know

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
aRegius, 2018-10-31
@MadInc

>>> x = [1, 2, [3, 4, 5, [6, 7], [8, [9, [10, 11], 12]], 13, 14], 15]
>>> from collections import Iterable
>>> def nested_to_flat(items):
          for i in items:
                if isinstance(i, Iterable):
                      yield from nested_to_flat(i)
                else:
                      yield i
>>> list(nested_to_flat(x))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question