List comprehension on 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']]

Now, what I want to do is convert each element in a list to float. My solution is this:

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

But can this be done using nested list comprehension, right?

what I’ve done is:

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

But then the result is bunch of 100’s with the sum of 2400.

any solution, an explanation would be much appreciated. Thanks!

13 Answers
13

Leave a Comment