Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to check if multiple items are (or are not) in a list? [duplicate]

Tags:

python

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.

like image 643
pyni Avatar asked Mar 26 '14 21:03

pyni


People also ask

How do you check if an element is in a list more than once?

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().

How do you check if a list contains items from another list?

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.


2 Answers

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
like image 161
Ffisegydd Avatar answered Oct 01 '22 23:10

Ffisegydd


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):
like image 27
John Kugelman Avatar answered Oct 02 '22 00:10

John Kugelman