CYLegends
CYLegends

Reputation: 53

Python: How to search for multiple items in a list

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.

Upvotes: 4

Views: 7391

Answers (5)

Samael
Samael

Reputation: 79

Depend on Paul Cornelius answer, I add something and some improvements to make it more understandable

number_list = [1, 2, 3, 4, 5]
search_nums = [1, 2]
if any(num in number_list for num in search_nums):
     # Is any number in search_nums inside of number_list do something
if all(num in number_list for num in search_nums):
     # Is all numbers in search_nums inside of number_list do something

Searching list in list of lists

list_number_list = [[1,2,3,4], [5,6,7,8]]
search_nums = [1, 2]
for number_list in list_number_list:
     if any(num in number_list for num in search_nums):
          # Is any number in search_nums inside of number_list do something
     if all(num in number_list for num in search_nums):
          # Is all numbers in search_nums inside of number_list do something

Upvotes: 0

Paul Cornelius
Paul Cornelius

Reputation: 10946

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

Upvotes: 6

Serg Anuke
Serg Anuke

Reputation: 168

If lists lenghs are long:

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_in = [2, 3, 4]
if len(set(_in)) == len(set(nums)&set(_in)):
    print("ok")

Upvotes: 0

Reblochon Masque
Reblochon Masque

Reputation: 36682

if 1 and 2 and 3 in my_num: 

is not doing what you think it does: it tests if 1 which is True, and if 2, which is also True, then if 3 in my_num

You must test for each condition individually:

if 1 and in my_num and 2 in my_num and 3 in my_num:

Upvotes: 0

duhaime
duhaime

Reputation: 27594

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

Upvotes: 3

Related Questions