rcmaea
Last Updated: August 20, 2017
·
44.04K
· terrasea
D0e601f16319d570eda75ab5a36733af

Flatten a list of lists in one line in Python

Sometimes you need to flatten a list of lists. The old way would be to do this using a couple of loops one inside the other. While this works, it's clutter you can do without. This tip show how you can take a list of lists and flatten it in one line using list comprehension.

The loop way

#The list of lists
list_of_lists = [range(4), range(7)]
flattened_list = []

#flatten the lis
for x in list_of_lists:
    for y in x:
        flattened_list.append(y)

List comprehension way

#The list of lists
list_of_lists = [range(4), range(7)]

#flatten the lists
flattened_list = [y for x in list_of_lists for y in x]

This is not rocket science, but it's cleaner, and, I'm lead to believe, faster than the for loop method.

Of coarse itertools comes to the rescue,as stated below in the comments by <a href="https://coderwall.com/iromli ">iromli</a>

list(itertools.chain(*listoflists))

Which is faster than any of the above methods, and flattening lists of lists is exactly what it was designed to do.

Say Thanks
Respond

3 Responses
Add your response

4586
D0e601f16319d570eda75ab5a36733af

Yeah that works too. Thanks. In fact the method you specify seems to be the fastest, followed by list comprehension, then distantly behind, the loop in a loop method.

over 1 year ago ·
22143
None

Good way:

import itertools
flattened_list  = list(itertools.chain(*list_of_lists))

;)

over 1 year ago ·
29122
Neo

Say this on another site ....
flattenedlist = sum(listof_lists, [])

28 days ago ·
Awesome Job

96b73d3e 7dde 11e7 8947 789166ad48cb
Sr. Computer Scientist
·
San Jose or San Francisco, Californ
·
Full Time