pythonlistnestedlist-comprehension

How can I use list comprehensions to process a nested list?


I have this nested list:

l = [['40', '20', '10', '30'], ['20', '20', '20', '20', '20', '30', '20'], ['30', '20', '30', '50', '10', '30', '20', '20', '20'], ['100', '100'], ['100', '100', '100', '100', '100'], ['100', '100', '100', '100']]

I want to convert each element in l to float. I have this code:

newList = []
for x in l:
    for y in x:
        newList.append(float(y))

How can I solve the problem with a nested list comprehension instead?


See also: How can I get a flat result from a list comprehension instead of a nested list?


Solution

  • Here is how you would do this with a nested list comprehension:

    [[float(y) for y in x] for x in l]
    

    This would give you a list of lists, similar to what you started with except with floats instead of strings.

    If you want one flat list, then you would use

    [float(y) for x in l for y in x]
    

    Note the loop order - for x in l comes first in this one.