0

I'm having a brain fart. How do I check if item is in list in python?

List = ['dog food', 'cat food', 'horse food'] If 'food' in List: False. Whyyyyyy

17th Oct 2019, 11:03 AM
Matt
4 ответов
+ 4
Your list is one thing, and the strings in them are something else. The string 'food' is not in the list, only longer strings that contain 'food', but you didn't ask for that. So you would have to ask for one of the strings directly, for example: If 'food' in List[0]: ... Or loop over them and check for each item: for item in List: if 'food' in item: ...
17th Oct 2019, 11:48 AM
HonFu
HonFu - avatar
+ 3
Avoid using `List` as variable name, it may lead to confusion. Use self explanatory names. food_list = ['dog food', 'cat food', 'horse food'] if any('food' in food_name for food_name in food_list): print("Got it!")
17th Oct 2019, 11:32 AM
Ipang
+ 2
a in b checks whether any item in b is equal to a. Because 'food' is not equal to any of the items in the list, it evaluated to False. Instead of: 'food' in List This would work: any('food' in item for item in List)
17th Oct 2019, 12:28 PM
Seb TheS
Seb TheS - avatar
0
are you trying to find ‘food’ in each string? List = ['dog food', 'cat food', 'horse food'] for i in List: if 'food' in i: print(False)
17th Oct 2019, 4:43 PM
Choe
Choe - avatar