I've been trying to debug this simple code for 20 minutes and it's driving me crazy, I'm starting to think there's a bug in Python. What I want to do is add two lists, element by element (there probably is some more efficient way to do this or even an in-build function, I'm just doing it as an exercise):
def add(l1,l2):
if l1>=l2:
l=l1
for i in range(len(l2)):
l1[i]+=l2[i]
else:
l=l2
for i in range(len(l1)):
l2[i]+=l1[i]
return l
Now for example:
add([1,2],[2,6,5])
[3, 8, 5]
But when the first number of the second list is negative, I get an error message:
add([1,2],[-2,6,5])
l1[i]+=l2[i]
IndexError: list index out of range
How can the sign of one element affect the index whatsoever?
To make things weirder, the code works just fine if I take out the if condition (I assume that the second list is longer here):
def add(l1,l2):
l=l2
for i in range(len(l1)):
l2[i]+=l1[i]
return l
Then:
>>> add([1,2],[-2,6,5])
[-1, 8, 5]
if l1>=l2? It does not compare the lengths of the lists, if that is what you intended...if l1 >= l2, which affects which list you decide to modify. You can tell something about this isn't right, because your code is trying to modifyl1butl2is the longer one.