Last Updated: May 04, 2024
·
337.8K
· terrasea

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.

13 Responses
Add your response

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 ·

Good way:

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

;)

over 1 year ago ·

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

over 1 year ago ·

That, to me, looks anything but clean. Looking at it, I would honestly have no idea what it did until running it. It's like you're sacrificing readability for conciseness a la the perl syndrome.

over 1 year ago ·

I for one do not find that hard to follow at all. If you have trouble understanding it, I'm sorry, but I don't agree with the assertion is anything but clean. If you don't think it's clean, how about sharing your clean method, rather than complaining about mine

over 1 year ago ·

Useful info! Thanks

over 1 year ago ·

Thanks. very useful

over 1 year ago ·

Thanks for sharing

over 1 year ago ·

Мery well)

over 1 year ago ·

Thank you for this useful tip!

over 1 year ago ·

Thank you sharing this answer its very helpful

over 1 year ago ·

well informed and right information.

over 1 year ago ·

Very valuable post. Thanks!

8 months ago ·