List comprehension on a nested list - How to do it in Python

0 votes

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?

Nov 21, 2018 in Python by Anirudh
• 2,080 points
1,234 views

1 answer to this question.

0 votes

Not sure what your desired output is, but if you're using list comprehension, the order follows the order of nested loops, which you have backwards. So I got the what I think you want with:

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

The principle is: use the same order you'd use in writing it out as nested for loops.

answered Nov 21, 2018 by Nymeria
• 3,560 points

Related Questions In Python

0 votes
1 answer

How to Print a List in Python

ou are using Python 2.x syntax with ...READ MORE

answered Aug 31, 2018 in Python by charlie_brown
• 7,720 points
752 views
0 votes
2 answers

How do I connect to a MySQL Database in Python?

connect mysql database with python import MySQLdb db = ...READ MORE

answered Mar 28, 2019 in Python by rajesh
• 1,270 points
1,572 views
0 votes
1 answer

“stub” __objclass__ in a Python class how to implement it?

You want to avoid interfering with this ...READ MORE

answered Sep 27, 2018 in Python by Priyaj
• 58,090 points
1,796 views
0 votes
1 answer

How to Reverse a list in Python

You can use the reversed function in ...READ MORE

answered Sep 29, 2018 in Python by SDeb
• 13,300 points
631 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,007 views
0 votes
1 answer
0 votes
1 answer

How do you add a background thread to flask in Python?

The example below creates a background thread ...READ MORE

answered Nov 19, 2018 in Python by Nymeria
• 3,560 points
36,185 views
0 votes
1 answer

Question on PyQt: How to connect a signal to a slot to start a background operation in Python

It shouldn't matter whether the connection is ...READ MORE

answered Nov 27, 2018 in Python by Nymeria
• 3,560 points
1,520 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP