Your elif
will end the loop (because of the break
) if the search
wasn't found at the first position (because the if
and elif
are executed for each item in your list). In your case you could simply use a "trigger" to indicate at least one finding and do the if
after the loop:
found = False
for n in range(len(lista)):
if str(search) in lista[n]:
print(lista[n])
found = True
if not found:
print("search not found in list")
However better would be to iterate over the list directly instead of a range of the length:
found = False
for item in lista:
if str(search) in item:
print(item)
found = True
if not found:
print("search not found in list")
If you don't like the trigger you can also use a conditional comprehension to get all the matches and use the number of matches as indirect trigger:
findings = [item for item in lista if str(search) in item]
if findings: # you got matches:
for match in findings:
print(match)
else: # no matches
print("search not found in list")