Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Loop Double Printing

Using the code below, I am able to get the correct answer, however it is repeated twice.

For instance, I would only want a result of [1.2038, 1.206], but the code below prints [1.2038, 1.206, 1.2038, 1.206]. Anybody knows what is wrong with my code? Any help would be greatly appreciated. Thanks!

spot = [1.2020, 1.2040]
forwardSwap = [0.0018, 0.0020]
forwardOutright = []

for i in range(len(spot)):
    for i in range(len(forwardSwap)):
        forwardOutright.append(spot[i] + forwardSwap[i])

print forwardOutright
like image 494
Jing Yi Avatar asked Oct 30 '17 13:10

Jing Yi


2 Answers

You should zip instead of a nested loop to iterate both lists concurrently:

forwardOutright = [x+y for x, y in zip(spot, forwardSwap)]
like image 123
Moses Koledoye Avatar answered Oct 15 '22 18:10

Moses Koledoye


As per the given code in your question, both of your loops are using a variable named as i.

for i in range(len(spot)):
    for i in range(len(forwardSwap)):
like image 25
Nandeep Mali Avatar answered Oct 15 '22 17:10

Nandeep Mali