If I have three lists of strings like the below how do I iterate through the list in order to identity if a specified ingredient say 'banana' is in any of the lists? I need to define a function that outputs either true or false.
menu = [
['soup','onion','potato','leek','celery'],
['pizza','bread','tomato','cheese','cheese'],
['banana']
]
CodePudding user response:
You need to check in each of the sub-lists, you can use any
built-in passing the generator expression
>>> any('banana' in v for v in menu)
True
CodePudding user response:
Credit to @ThePyGuy for the logic, but here is a very similar answer, defined as a function.
def check_menu(item, menu):
if any(item in v for v in menu):
return True
else:
return False
print(check_menu('banana',menu))
True
print(check_menu('mushroom',menu))
False
This way you can have it check whatever menu, or item in the menu you want.
CodePudding user response:
use "any" if only one is enough, if you seek that word in "all" list use all :)