Posted By

alces on 12/03/14


Tagged

list python tuple immutable flatten


Versions (?)

Flatten a list of lists (any depth) in Python


 / Published in: Python
 

URL: py_flatten_list

Flatten a list of lists (or tuple of tuples, list of tuples, etc.) to any depth of nesting using no mutable objects.

  1. def flat(lst):
  2. '''
  3. return a tuple making from all values from the flatten list of lists (or tuple of tuples, etc.)
  4. '''
  5. return reduce(lambda l, e: (isinstance(e, list) or isinstance(e, tuple)) and l + flat(e) or l + (e,), lst, ())
  6.  
  7. assert flat([]) == ()
  8. assert flat((1,)) == (1,)
  9. assert flat([1, 2, 3]) == (1, 2, 3)
  10. assert flat([(1,2),[3,4,[5,6]],7,8,(9,(0,))]) == (1, 2, 3, 4, 5, 6, 7, 8, 9, 0)

Report this snippet  

You need to login to post a comment.