Skip to content

Instantly share code, notes, and snippets.

@gosuto-inzasheru
Created December 30, 2018 10:14
Show Gist options
  • Save gosuto-inzasheru/b6deccd3fd5fefbabb72759c74040745 to your computer and use it in GitHub Desktop.
Save gosuto-inzasheru/b6deccd3fd5fefbabb72759c74040745 to your computer and use it in GitHub Desktop.
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
@gosuto-inzasheru
Copy link
Author

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

@gosuto-inzasheru
Copy link
Author

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