So i have a list with number values such as my_num = [1,2,2,3,4,5]
What i want is a code that will check if 1, 2 and 3 are in the list. What i had in mind was:
if 1 and 2 and 3 in my_num:
do something
but the problem is if 1 and 3 are in the list the do something code executes anyways even without the 2 being there.
Check out the standard library functions any
and all
. You can write this:
if any(a in my_num for a in (1, 2, 3)):
# do something if one of the numbers is in the list
if all(a in my_num for a in (1, 2, 3)):
# do something if all of them are in the list
Try this:
nums = [1,2,3,4]
>>> if (1 in nums) and (2 in nums) and (3 in nums):
... print('ok')
...
ok
>>> if (1 in nums) and (2 in nums) and (9 in nums):
... print('ok')
...
>>>
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