Reputation: 123
I have this code snippet : I was expecting the output to be [1,1] when I print the list but I'm getting [0,0]. Since I have already initialised a and b as list variables , I thought the value of "result" would be updated to the values of a and b after the loop. My program is working fine if I return the values a and b but I was just wondering why the "result" isn't getting updated. I'm still learning Python so would appreciate any help
a=0 b=0 arrayA=[7,9,1] arrayB=[2,9,5] result=[a,b] for i in range(0,len(arrayA)): if(arrayA[i]>arrayB[i]): a+=1 elif (arrayA[i]==arrayB[i]): continue else: b+=1 print(result)
Blockquote
Thank you!
Upvotes: 0
Views: 36
Reputation: 4973
complected objects like list (and more) get passed by reference, so this will get you the answer you want
a=[0]
b=[0]
arrayA=[7,9,1]
arrayB=[2,9,5]
result=[a,b]
for i in range(0,len(arrayA)):
if(arrayA[i]>arrayB[i]):
a[0]+=1
elif (arrayA[i]==arrayB[i]):
continue
else:
b[0]+=1
print(result)
Upvotes: 1
Reputation: 2750
result = [a,b], the variables a and b are not references.
a=0
b=0
arrayA=[7,9,1]
arrayB=[2,9,5]
for i in range(0,len(arrayA)):
if(arrayA[i]>arrayB[i]):
a+=1
elif (arrayA[i]==arrayB[i]):
continue
else:
b+=1
result=[a,b]
print(result)
Would be what you want
Upvotes: 1