Shravya Mutyapu
Shravya Mutyapu

Reputation: 318

"in" operator not working as expected?(python)

I am a beginner at python when I was going through the operators concept. I got stuck. Can someone help me out?? Why isn't the in operator returning true??

list1 = [1,2,3]
list2 = [1,2,3,4,5] 
print(list1 in list2)`

Instead, it returns false.

list1 = [1,2,3]
list2 = [1,2,3] 
print(list1 in list2)`

returns false in both cases.

Upvotes: 1

Views: 450

Answers (2)

RAW_tech
RAW_tech

Reputation: 65

As Chepner said, list1 in list2 checks if list1 is in list2. What you can do, is check if each element from list1 is in list2 using a for loop:

for i in list1:
    if i in list2:
        print(i)

This will print out all the elements which are found in both list1 and in list2.

What you can also do, which is a lot quicker answer is use sets. First, make list1 and list2 into a set:

set_list1 = set(list1)
set_list2 = set(list2)

You can also write a set without starting from a list:

set_list1 = {1,2,3}
set_list2 = {3,4,5}

Notice that, in sets, you use {} not []

Then, here are a few things you can do with sets:

print(set_list1 | set_list2)  # Union - {1,2,3,4,5}
print(set_list1 & set_list2)  # Intersection - {3}
print(set_list1 - set_list2)  # Difference - {1,2}
print(set_list2 - set_list1)  # Difference - {4,5}
print(set_list1 ^ set_list2)  # Symmetric difference - {1,2,4,5}

I hope this helped.

Upvotes: 1

chepner
chepner

Reputation: 530930

list1 in list2 doesn't check if each element of list1 is contained in list2; it checks if list1 itself is an element of list2:

>>> [1, 2, 3] in [1, 2, 3]
False
>>> [1, 2, 3] in [[1, 2, 3]]
True

You can use the all function to automate the element-wise check:

>>> all(x in list2 for x in list1)
True

Upvotes: 6

Related Questions