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))
print(combined)
>> ['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]
print(flatten_iter(lists))
>> ['a', 'b', 'c', 'd', 'e', 'f']
Anyway yeah I thought that was a neat one-liner
Comments
Displaying 0 of 0 comments ( View all | Add Comment )