Reputation: 1
I'm writing a function (the long way) to test if a number I type in is in the list. I don't want to use the 'in' function. The question is why it only works when I type in numbers that are in the list and I get an error in line if x == a[i]:
when a number is not in the list.
def is_member(x):
a = [1,5,3,9,4,100]
i = 0
found = False
while found == False:
if x == a[i]:
found = True
break
i += 1
if found == True:
return "True"
else:
return "False"
Upvotes: 0
Views: 146
Reputation: 125
You can also use a for loop to avoid the index error, try this
def is_member(x):
a = [1,5,3,9,4,100]
for i in range(len(a)):
if x == a[i]:
return True
return False
Upvotes: 2
Reputation: 132098
Try something like this instead:
def is_member(x):
a = [1,5,3,9,4,100]
for i in a:
if i == x:
return "True"
return "False"
Here we iterate over a, and if any member == x
we return "True" right away. If we have not returned by the end of the loop then the element is not present.
Upvotes: 1
Reputation: 4441
def is_member(x):
a = [1,5,3,9,4,100]
i = 0
found = False
while found == False:
if i >= len(a):
return False # end of list reached
if x == a[i]:
found = True
break
i += 1
if found == True:
return "True"
else:
return "False"
to handle end of list, a piece of code has been added
In fact you do not another variable like Found
, you can do it in below way.
def is_member(x):
a = [1,5,3,9,4,100]
i = 0
while True:
if i >= len(a):
print 'test'
return False # end of list reached
if x == a[i]:
return True
i += 1
Upvotes: 1
Reputation: 21
That's because you are going outside the bounds of the list.
You should add a check so you can return when i > len(a)
.
Upvotes: 2
Reputation: 310
You need to add a condition that if (i == len(a)-1): return False
.
Because the index can not exceed the length of list a
.
Upvotes: 1
Reputation: 56527
If there is no element in the list, then your i
gets bigger and bigger until it becomes i = len(a)
. At this point a[i]
throws an IndexError
since you went above the list size. Simple fix would be to use while i < len(a):
instead of while found == false:
since you break the loop at x == a[i]
anyway.
Upvotes: 2