Flatten a list of lists (any depth) in Python


/ Published in: Python
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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)

URL: py_flatten_list

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.