garlfd garlfd - 1 year ago 110
Python Question

Flatten an iterable of iterables

How can I write

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 Source

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)
            yield x
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download