Home > Net >  Getting a bug when trying to add two lists in Python
Getting a bug when trying to add two lists in Python

Time:11-21

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]

CodePudding user response:

When you use comparison operators on lists you do not compare the length of them but the content, look:

l1 = [1, 2]
l2 = [2, 1]
assert l1 < l2 (because l1[0] < l2[0])

What you want to use is len builtin:

if len(l1) >= len(l2):
    ...

CodePudding user response:

You did an elementwise compare when really you wanted to know which was the shortest list for indexing. So, compare the lengths of the lists, not the contents. To avoid duplicating the logic, setup the relationship once for the rest of the function.

def add(l1,l2):
    large, small = (l1, l2) if len(l1) >= len(l2) else (l2, l1)
    for i in range(len(small)):
        large[i]  = small[i]
    return large

print(add([1,2], [2,6,5]))
print(add([1,2], [-2,6,5]))
  • Related