Reputation: 11
How can I rewrite the function below to search from the end of the list?
def search(list,n):
for i in range(len(list)):
if list[i] == n:
return True
return False
Upvotes: 0
Views: 622
Reputation: 35
You could iterate backwards through the list. For that you need to specify your range with three parameters. The first would be the starting point, the second the endpoint, and the third would be the increment. That's better than reversing it in runtime matters. Try this:
def search(list, n):
for i in range(len(list)-1, 0, -1):
print(list)
if list[i]=n:
return True
return False
Upvotes: 1
Reputation: 190
Use list.reverse()
to reverse your list so that you are starting from the end:
list= [1,2,3,4,5,6,7,8,9]
n=(3)
list.reverse()
def search(list,n):
for i in reversed(range(len(list))):
print(list)
if list[i] == n:
return True
return False
search(list,n)
Upvotes: 0