Monday, June 11, 2018

Python Flatten List of Lists (Magic)

How does this work?

l_of_lists = [list(range(10)), list(range(20,30)), list(range(50,60))]

[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]]

>>> l = [y for x in l_of_lists for y in x]
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59]

https://coderwall.com/p/rcmaea/flatten-a-list-of-lists-in-one-line-in-python

No comments: