Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through multiple lists with same index position in python

I am new to python and I was just trying some list manipulations. I have three lists

A = [10,20,30,40,50,60]
B = [22,44,66,88,12,10]
C = [2,4,6,8,10,20]

I want to iterate over these three lists and for each value of C I want to add half of that value to the corresponding values of A and B. For example for the 1st iteration - half = 2/2= 1 So A = 10 + 1 and B = 22+1 So the final lists should look something like this

A = [11,22,33,44,55,70]
B = [23,46,69,92,17,20]
C = [2,4,6,8,10,20]
like image 474
newbie Avatar asked Mar 20 '23 03:03

newbie


2 Answers

As long as the lists all have the same lengths, you can iterate with enumerate() function:

for i, n in enumerate(C):
    A[i] += n/2
    B[i] += n/2

>>> A
[11, 22, 33, 44, 55, 70]
>>> B
[23, 46, 69, 92, 17, 20]
like image 137
Paulo Bu Avatar answered Mar 26 '23 14:03

Paulo Bu


>>> A, B = zip(*((a + c/2, b + c/2) for a, b, c in zip(A, B, C)))
like image 30
behzad.nouri Avatar answered Mar 26 '23 15:03

behzad.nouri