user16440950
user16440950

Reputation:

Python nested for loop issues

I am trying to use a nested for loop to simply add two sets of numbers together respectively.

x=[1,2,3,4]
f=[0,1,2,3]

for i in x:
    for j in f:
        ans = i+j
        ans2 = j
print(ans,ans2)

My output is

6 5
7 5
8 5
9 5

However, I want it to be

 1 0
 3 1
 5 2
 7 3

I'm not quite sure where i'm going wrong and any help would be appreciated.

Upvotes: 0

Views: 55

Answers (1)

Nick
Nick

Reputation: 147146

You need to use the index into x to get the appropriate value of f to use as j. You can do this by iterating over the enumerated x:

x=[1,2,3,4]
f=[0,1,2,3]

for idx, i in enumerate(x):
    j = f[idx]
    ans = i+j
    ans2 = j
    print(ans,ans2)

Alternatively you could use zip and iterate both values at once:

for i, j in zip(x, f):
    ans = i+j
    ans2 = j
    print(ans,ans2)

In both cases the output is:

1 0
3 1
5 2
7 3

Upvotes: 2

Related Questions