Why this function is not returning [0,0,7]?

Viewed 32

Why it's returning False instead of True? What's wrong with my code? Why it isn't returning [0,0,7]?

model_neschimbat = [0,0,7]
def spy2(lista):
    
    ce_a_iesit = []
    model = [0, 0, 7]
    model_neschimbat = [0,0,7]
    for i in range(0,len(lista) - 1):
        if lista[i] == model[0]:
            ce_a_iesit.append(lista[i])
            model.pop(0)
    print(ce_a_iesit)
    if ce_a_iesit == model_neschimbat:
        return True
    else:
        return False
2 Answers

You are modifying the model variable inside the loop, so it is not the same as model_neschimbat when the loop ends. You can use list.copy() to create a copy of the list:

model = [0, 0, 7]
model_neschimbat = model.copy()

The problem is with the for loop, specifically

for i in range(0,len(lista) - 1):

You are going from [0, len(lista) - 1), which means that you skip the last element. Just change len(lista) - 1 to len(lista).

TLDR; the upper bound in a Python for loop is exclusive.

Related