Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I convert a list to float inside a for statement

I have multiple lists of numerators and denominators that I’m counting as I parse through a site to get variables that I want to turn into fractions. (eg. a = [1, 2] should be converted to a = 0.5).

I’ve tried this:

a = [1, 2]
b = [3, 5]

for i in a, b:
  i = i[0]/i[1]
  print(i)

print(a, b)

and I get:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>>> 0.5
>>> 0.6
>>> [1, 2] [3, 5]

The variables return the output I’m looking for when printed inside the for statement but not outside. How can I fix this? For loop isn’t necessary, if there’s an easier way to do it I’m all ears.

(I’m using Python 3.10)

@Eli Harold:

>>> a = [1, 2]
>>> b = [1, 4]
>>> for i in a, b:
...     i = i[0]/i[1]
... 
>>> print(a)
[1, 2]
>>> print(b)
[1, 4]

>Solution :

You can use a list comprehension:

c = [ n/d for n,d in [a,b] ] 

print(c)
[0.5, 0.6]
  • for ... in [a,b] will iterate through each list one by one
  • n,d will be unpacked from the first and second item of each list
  • [ n/d ... ] build a resulting list with each n and d provided by the for

you could assign the result to the original variables if needed:

a,b = ( n/d for n,d in [a,b] ) 

print(a,b)
0.5 0.6
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading