-5

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}

Divide
  • 1
  • 2
  • 1
    "As both should simply compare the elements in both sets and result in common elements." No, as you're already aware, they are separate operators. You should not expect them to behave identically; that's the whole point of them being distinct. `and` is a *logical` AND operator: it operates on the truthiness of its operands. – jamesdlin Apr 08 '23 at 02:49
  • 1
    You are simply wrong about the what `and` does. It isn't clear *why* you believe what you believe, but it is wrong. That is the simple answer to your question – juanpa.arrivillaga Apr 08 '23 at 03:34

1 Answers1

0

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 }

Nick
  • 138,499
  • 22
  • 57
  • 95