Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way of checking if several elements are in a list

Tags:

python

list

I have this piece of code in Python:

if 'a' in my_list and 'b' in my_list and 'c' in my_list:
    # do something
    print my_list

Is there a more pythonic way of doing this?

Something like (invalid python code follows):

if ('a', 'b', 'c') individual_in my_list:
    # do something
    print my_list
like image 766
Pablo Santa Cruz Avatar asked Nov 17 '11 14:11

Pablo Santa Cruz


People also ask

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

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 all elements are in a list Python?

Use the all() function to check if all elements in a list are True , e.g. if all(item is True for item in my_list): . The all() function will return True if all of the values in the list are equal to True and False otherwise. Copied!

How do you check if a list contains an element?

The most convenient way to check whether the list contains the element is using the in operator. Without sorting the list in any particular order, it returns TRUE if the element is there, otherwise FALSE. The below example shows how this is done by using 'in' in the if-else statement.


2 Answers

if set("abc").issubset(my_list):
    # whatever
like image 85
Sven Marnach Avatar answered Nov 15 '22 05:11

Sven Marnach


The simplest form:

if all(x in mylist for x in 'abc'):
    pass

Often when you have a lot of items in those lists it is better to use a data structure that can look up items without having to compare each of them, like a set.

like image 30
Jochen Ritzel Avatar answered Nov 15 '22 06:11

Jochen Ritzel