garlfd garlfd - 1 month ago 16
Python Question

Flatten an iterable of iterables

How can I write

function
which should return every value nested in an iterable?

Here's an example of what I'm trying to accomplish:

for i in function([1, 2, [3, 4, (5, 6, 7), 8, 9], 10]):
print(i, end=' ')


Expected output:

1 2 3 4 5 6 7 8 9 10

wim wim
Answer

Python 2 users have a built-in for this task:

from compiler.ast import flatten

Unfortunately, it has been removed in python 3. You can roll your own though:

from collections import Iterable

def flatten(collection):
    for x in collection:
        if isinstance(x, Iterable) and not isinstance(x, str):
            yield from flatten(x)
        else:
            yield x
Comments