Home > Back-end >  Check that elements exist within a list Python
Check that elements exist within a list Python

Time:04-27

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')

CodePudding user response:

You can do it as a simple set logic.

set(pattern).issubset(foods)

CodePudding user response:

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

CodePudding user response:

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')

CodePudding user response:

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)
  • Related