Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 }

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading