#12
Inspired Python
def flatten(l):
    match l:
        case (list() | tuple() | set()) as items:
            for item in items:
                yield from flatten(item)
        case _:
            yield l

>>> list(flatten([[1, 2], {"site": "inspiredpython.com"},
         "Inspired Python", [3, [4], [5, (6, (7, 8))]]]))
[1, 2, {'site': 'inspiredpython.com'}, 'Inspired Python', 3, 4, 5, 6, 7, 8]

Pattern Matching: Flattening deeply-nested lists


It’s easy enough to flatten a single level of lists, but merging arbitrarily deep lists of lists (or sets and tuples!) is easily done with the new pattern matching feature. This implementation is clever enough not to trip up when it encounters strings or dictionaries, which are also iterable.

Be Inspired Get Python tips sent to your inbox

We'll tell you about the latest courses and articles.

Absolutely no spam. We promise!