I'm trying to write a Pyhon function that checks whether a list contains a given index number.
def ncheck(n, list):
for x in range(len(list)):
if n == x:
return True
else:
return False
I tested the code with the following arguments:
print(ncheck(6, [0, 1, 2, 3]))
print(ncheck(2, [0, 1, 2, 3]))
I expected the first run to return False
since it's looking for index 6 on a list with 4 elements and the second run to return True
because it's looking for index 2. What actually happens is both runs return False
. I thought that maybe having return
inside the if block caused the problem, so I tried assigning another variable "answer" inside the if block and returning this variable as the closing statement for the function but got the same result:
def ncheck(n, list):
for x in range(len(list)):
if n == x:
answer = True
else:
answer = False
return answer
print(ncheck(6, [0, 1, 2, 3]))
print(ncheck(2, [0, 1, 2, 3]))
False
False
I'm at a loss. More than an alternate way to solve this issue, I want to understand why this method specifically isn't working.