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:
>>> 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 onen,dwill be unpacked from the first and second item of each list[ n/d ... ]build a resulting list with eachnanddprovided by thefor
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