a neat python trick

so I've been trying some stuff out with the walrus operator lately and I found this to be a helpful little trick to combine all elements of a depth-1 nested list structure:

lists = [['a', 'b'], ['c', 'd'], ['e', 'f']]
combined, _ = (combined := list()), list(map(combined.extend, lists))

>> ['a', 'b', 'c', 'd', 'e', 'f']

This is obviously a really basic example, but if you wrap it up in a function it makes a great handler for nested iterable structures:

lists = [['a', 'b'], ['c', 'd'], ['e', 'f']]
def flatten_iter(data:iter) -> list:
    return ((combined:=list()), *map(combined.extend, lists))[0]


>> ['a', 'b', 'c', 'd', 'e', 'f']

Anyway yeah I thought that was a neat one-liner

0 Kudos


Displaying 0 of 0 comments ( View all | Add Comment )