0

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]
3
  • 2
    What is the purpose of if l1>=l2? It does not compare the lengths of the lists, if that is what you intended... Commented Nov 20, 2022 at 22:54
  • The sign of the elements affects the outcome of 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 modify l1 but l2 is the longer one. Commented Nov 20, 2022 at 22:57
  • Oh my god, yes I obviously intended to compare the lenghts of the lists. I didn't even know it was possible to compare two lists. Thanks you Commented Nov 20, 2022 at 23:02

2 Answers 2

1

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):
    ...
Sign up to request clarification or add additional context in comments.

Comments

0

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]))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.