Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Flatten Python lists and tuples into their individual items
def flatten(li):
"""Flatten lists or tuples into their individual items. If those items are
again lists or tuples, flatten those."""
if isinstance(li, (list, tuple)):
for item in li:
yield from flatten(item)
else:
yield li
@jorijnsmit

This comment has been minimized.

Copy link
Owner Author

jorijnsmit commented Dec 30, 2018

You could make this broader/more complex by checking for instances of abstract base classes instead of (list, tuple).

@jorijnsmit

This comment has been minimized.

Copy link
Owner Author

jorijnsmit commented Dec 30, 2018

Taken from this discussion on Stack Overflow: Flatten an irregular list of lists

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.