0

I have this code:

def num(list, target):
    index = []
    for i in list:
        for x in list:
            if i + x == target:
                index.append(list.index(i))
                index.append(list.index(x))
                break
    print(index)

li = [1, 7, 11, 2, 15]
num(li, 9)

I expected to get [1,3], but the result is [1,3,3,1]. Why?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • perhaps try printing what `i` and `x` are during the loop, might be a helpful debugging step. – Chris Aug 07 '21 at 16:34
  • 3
    It `break`s the `for x in list` loop, but not the `for i in list` loop. As an aside, you should use a different name instead of `list`; that hides the built-in name. – Karl Knechtel Aug 07 '21 at 16:34

0 Answers0