Can you please explain why does this function prints -1
only once, when it has to print it on each loop cycle? However, when I remove line 9 return -1
, it prints -1
4 times, as it should be. How does it work?
def find_index(to_search, target):
enum_tuple = tuple(enumerate(to_search))
# print(enum_tuple)
for i, value in enum_tuple:
if value == target:
break
else:
print(-1)
return -1
return i
my_list = ["Rick", "Amy", "Jack", "Mary"]
index_location = find_index(my_list, "Tom")
This happens because when you reach line 9 return -1
you are exiting the function find_index
so the loop won't continue running.