Skip to content Skip to sidebar Skip to footer

Simplest Way To Check If Multiple Items Are (or Are Not) In A List?

I want to use syntax similar to this: if a in b but I want to check for more than one item, so I need somthing like this: if ('d' or 'g' or 'u') in a but I know it doesn't work.

Solution 1:

any and all can be used to check multiple boolean expressions.

a = [1, 2, 3, 4, 5]
b = [1, 2, 4]

print(all(i in a for i in b)) # Checks if all items are in the listprint(any(i in a for i in b)) # Checks if any item is in the list

Solution 2:

Use any plus a generator:

ifany(x in d for x in[a, b,c]):

Or check for set intersection:

if {a, b, c} & set(d):

Post a Comment for "Simplest Way To Check If Multiple Items Are (or Are Not) In A List?"