Home > Enterprise >  Find if value is present in list
Find if value is present in list

Time:12-04

I'm trying to find if 2 is present in a, but when I run the code it says its not here

a = [1,2,3]
b = [2]

if b in a:
    print('its here')
else:
    print('its not here')

From what I read online I see in operator used to check if a value is in an array. although if I use: if 2 in a: then It shows as its here but I would like b to do that.

CodePudding user response:

You are searching a for a list containing 2, not for the value 2 itself. (b is a list not a value)

You could get it to work by using the first element of the b:

if b[0] in a:
    print('its here')
else:
    print('its not here')

Or you could check if all values of list b are present in list a

if all(value in a for value in b):
    print('its here')
else:
    print('its not here')

CodePudding user response:

You can use the for loop to check if the b is in a or vice versa.

Here I made a example like this:

a = [1, 2, 3]
b = [2]

for x in a, b:
    if x == b:
        print("b is in a")
    else:
        print("b is not in a")

Now over the print you can put the text you want, like "B is here".

  • Related