Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to search for multiple items in a list

Tags:

python

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.

like image 428
CYLegends Avatar asked Oct 18 '25 16:10

CYLegends


2 Answers

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
like image 143
Paul Cornelius Avatar answered Oct 21 '25 07:10

Paul Cornelius


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')
...
>>>
like image 35
duhaime Avatar answered Oct 21 '25 05:10

duhaime