Skip to content
Advertisement

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

I have this nested list:

JavaScript

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

JavaScript

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?

Advertisement

Answer

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

JavaScript

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

JavaScript

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

Advertisement