If you make for i in (l, p, c)
the for
iterates over the list tuple (l, p, c)
so iterates 3 times and in each of them i
will refer to one of the lists.
To iterate over items of several iterables of the same length in parallel use the built-in zip
Then in each iteration you just have to add the result to an empty list created before starting the for
using the method list.append()
l = [36.83, 31.75, 43.815, 36.83, 32.06, 45.08, 35.88]
p = [0.77, 0.48, 1.16, 0.73, 0.48, 1.39, 0.65]
c = [24.77, 21.29, 27.94, 24.77, 21.59, 31.75, 22.86]
r = []
for vl, vc in zip(l, c):
k = (vl * vc**2) / 29
r.append(k)
For more efficiency use lists by compression:
l = [36.83, 31.75, 43.815, 36.83, 32.06, 45.08, 35.88]
p = [0.77, 0.48, 1.16, 0.73, 0.48, 1.39, 0.65]
c = [24.77, 21.29, 27.94, 24.77, 21.59, 31.75, 22.86]
r = [(vl * vc**2) / 29 for vl, vc in zip(l, c)]
You can use an external function if you need to calculate each item:
l = [36.83, 31.75, 43.815, 36.83, 32.06, 45.08, 35.88]
p = [0.77, 0.48, 1.16, 0.73, 0.48, 1.39, 0.65]
c = [24.77, 21.29, 27.94, 24.77, 21.59, 31.75, 22.86]
def foo(l, c):
return (vl * vc**2) / 29
r = [foo(vl, vc) for vl, vc in zip(l, c)]
#r = [foo(*values) for values in zip(l, c)]
In any case the result is:
>>> r
[779.212183,
496.24604051724134,
1179.4448046206896,
779.212183,
515.3126512413794,
1567.015775862069,
646.5571051034483]
I have excluded p
from the cycle because you do not use it in the code that you show, but if you require it the idea is the same, for vl, vp, vc in zip(l, p, c)
.
Note: If using Python 2 it is better to use itertools.izip
and not the built-in zip
. The latter in Python 2 returns a list, not an iterator like it does in Python 3, so we create a temporary list in memory that is not necessary.