Skip to content

Instantly share code, notes, and snippets.

@BoeingX
Created April 8, 2018 10:11
Show Gist options
  • Select an option

  • Save BoeingX/f5283bd817a4f9ab71c7f76957fdc274 to your computer and use it in GitHub Desktop.

Select an option

Save BoeingX/f5283bd817a4f9ab71c7f76957fdc274 to your computer and use it in GitHub Desktop.
Recursively flatten a nested iterable
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import collections
def flatten(lst):
"""Flatten a iterable.
>>> from __future__ import print_function
>>> lst = [[1, 2], [], [1, [[2, 3], 3]], 4, 5]
>>> print(flatten(lst))
[1, 2, 1, 2, 3, 3, 4, 5]
"""
assert(isinstance(lst, collections.Iterable))
if not len(lst):
return lst
head, *tail = lst
if isinstance(head, collections.Iterable):
return flatten(head) + flatten(tail)
return [head] + flatten(tail)
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment