0

Is there a way to check that Elements within list1 are part of list2? What I've tried is down below... But I don't get an ouput. I'm guessing the 'in' function only deals with individual elements?

pattern=['Tacos', 'Pizza'] Foods=['Tacos', 'Pizza', 'Burgers', 'Fries', 'Ice-cream'] if pattern in foods: print('yes') 
2
  • 1
    It's not clear from your post what exactly you want to achieve. Do you want to test if any of the strings is contained in foods, or all of them? And if all, do they have to be consecutive? Or just in that order? Or can they be in any order? Commented Apr 26, 2022 at 19:30
  • Given the accepted answer, this seems to be a duplicate of stackoverflow.com/questions/16579085/… Commented Apr 26, 2022 at 19:47

4 Answers 4

4

You can do it as a simple set logic.

set(pattern).issubset(foods) 
Sign up to request clarification or add additional context in comments.

Comments

0

Using set logic:

>>> set(pattern).issubset(foods) True 

Using iteration over the lists (this is less efficient in general, especially if pattern is long, but it's useful to understand how this works where your original in check didn't):

>>> all(food in foods for food in pattern) True 

Comments

0

Substract foods from pattern and the list should be empty.

len( set(pattern) - set(Foods) ) == 0 

or, intersection should be equal to the length of the pattern

len( set(pattern) & set(Foods) ) == len(pattern) 

Comments

0

Because pattern is a list but you want to check every element inside the pattern list then you need to use a loop.

pattern=['Tacos', 'Pizza'] Foods=['Tacos', 'Pizza', 'Burgers', 'Fries', 'Ice-cream'] for patt in pattern: if patt in foods: print('yes') 

Comments