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.
so I did it this way:
for i in a:
for j in ['d','g','u']:
if i==j
and it worked, but I wonder if there's a simpler way.
Using Count() The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count().
There are 2 ways to understand check if the list contains elements of another list. First, use all() functions to check if a Python list contains all the elements of another list. And second, use any() function to check if the list contains any elements of another one.
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 list
print(any(i in a for i in b)) # Checks if any item is in the list
Use any
plus a generator:
if any(x in d for x in [a, b, c]):
Or check for set intersection:
if {a, b, c} & set(d):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With