6

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
Juxhin
  • 5,068
  • 8
  • 29
  • 55
Jing Yi
  • 203
  • 4
  • 15

7 Answers7

21

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

forwardOutright = [x+y for x, y in zip(spot, forwardSwap)]
akash karothiya
  • 5,736
  • 1
  • 19
  • 29
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
3

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)):
Nandeep Mali
  • 4,456
  • 1
  • 25
  • 34
3

This should work

list(map(lambda i: sum(i), zip(spot, forwardSwap)))
daemon24
  • 1,388
  • 1
  • 11
  • 23
3

The problem you have is caused by the fact that the inner loop is executed completely every time the outer loop is executed. i.e for every item in spot you are going through every item in forwardSwap and appending a new value to forwardOutright. Instead you want a one-to-one matching between these two lists, so you could use:

for i,j in zip(spot, forwardSwap): forwardOutright.append(i+j)

You should also avoid shadowing your variables, i.e using i in both loops, instead you could use i and j for example. Otherwise this will cause your program to execute in unexpected ways.

1

Because you have nested for loops, the outer loop is run as many times as there are elements of spot and the inner loop is run as many times as the product of the lengths. Instead you should use zip:

for s, fs in zip(spot, forwardSwap):
    forwardOutright.append(s + fs)

Or you can use a list comprehension:

forwardOutright = [s + fs for s, fs in zip(spot, forwardSwap)]
yinnonsanders
  • 1,831
  • 11
  • 28
1

You just need to loop over once:

spot = [1.2020, 1.2040]
forwardSwap = [0.0018, 0.0020]
forwardOutright = []
for i in range(len(spot)):
    forwardOutright.append(forwardSwap[i]+spot[i])

Outout:

[1.2038, 1.206]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

You have two nested loops that run twice each.

Therefore you execute the code inside the second loop (2x2) 4 times.

rwms
  • 313
  • 1
  • 5
  • 15