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
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().
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!
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.
if set("abc").issubset(my_list):
# whatever
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
.
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