Search code examples
pythonpython-3.xlistsetset-intersection

Why does "set(a) and set(b)" vs "set(a) & set(b)" give different results in python?


I understand that one is bitwise operation while the other is not, but how does this bitwise property affect the results of given expression. As both should simply compare the elements in both sets and result in common elements.

set(a) & set(b) gives the correct answer while finding common elements in set(a) and set(b), while set(a) and set(b) gives wrong answer.

Python code:

nums2 = [9,4,9,8,4]
nums1 = [4,9,5]

a = set(nums1) and set(nums2)
b = set(nums1) & set(nums2)

print(a)
print(b)

Results: a = {8, 9, 4} b = {9, 4}


Solution

  • As described in the documentation:

    The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

    Thus

    set(nums1) and set(nums2)
    

    first evaluates set(nums1) which is { 9, 4, 5 } (which is not false - see the documentation) and thus the expression returns set(nums2) i.e. { 8, 9, 4 }.

    By contrast, also as described in the documentation:

    set(nums1) & set(nums2)
    

    evaluates to the intersection of the two sets, which is { 9, 4 }