Flatten list of lists

Hellfish picture Hellfish · Jun 29, 2012 · Viewed 277.6k times · Source

I'm having a problem with square brackets in Python. I wrote a code that produces the following output:

[[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]

But I would like to perform some calculations with that, but the the square brackets won't let me.

How can I remove the brackets? I saw some examples to do that but I could not apply them to this case.

Answer

Paul Seeb picture Paul Seeb · Jun 29, 2012

Flatten the list to "remove the brackets" using a nested list comprehension. This will un-nest each list stored in your list of lists!

list_of_lists = [[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
flattened = [val for sublist in list_of_lists for val in sublist]

Nested list comprehensions evaluate in the same manner that they unwrap (i.e. add newline and tab for each new loop. So in this case:

flattened = [val for sublist in list_of_lists for val in sublist]

is equivalent to:

flattened = []
for sublist in list_of_lists:
    for val in sublist:
        flattened.append(val)

The big difference is that the list comp evaluates MUCH faster than the unraveled loop and eliminates the append calls!

If you have multiple items in a sublist the list comp will even flatten that. ie

>>> list_of_lists = [[180.0, 1, 2, 3], [173.8], [164.2], [156.5], [147.2], [138.2]]
>>> flattened  = [val for sublist in list_of_lists for val in sublist]
>>> flattened 
[180.0, 1, 2, 3, 173.8, 164.2, 156.5, 147.2,138.2]