/ Published in: Python
Flatten a list of lists (or tuple of tuples, list of tuples, etc.) to any depth of nesting using no mutable objects.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
def flat(lst): ''' return a tuple making from all values from the flatten list of lists (or tuple of tuples, etc.) ''' return reduce(lambda l, e: (isinstance(e, list) or isinstance(e, tuple)) and l + flat(e) or l + (e,), lst, ()) assert flat([]) == () assert flat((1,)) == (1,) assert flat([1, 2, 3]) == (1, 2, 3) 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