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')
  • 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? – mkrieger1 Apr 26 '22 at 19:30
  • Given the accepted answer, this seems to be a duplicate of https://stackoverflow.com/questions/16579085/how-can-i-verify-if-one-list-is-a-subset-of-another – mkrieger1 Apr 26 '22 at 19:47

4 Answers4

4

You can do it as a simple set logic.

set(pattern).issubset(foods)
theherk
  • 6,954
  • 3
  • 27
  • 52
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')
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
codester_09
  • 5,622
  • 2
  • 5
  • 27
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)
Dieter
  • 2,499
  • 1
  • 23
  • 41
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
Samwise
  • 68,105
  • 3
  • 30
  • 44