im curious about how the logical operators work in sets. cosider this:
x = set('abcde')
y = set('bdxyz')
# union
print(x | y) # output: {'d', 'b', 'y', 'e', 'z', 'x', 'c', 'a'}
print(x or y) # output: {'d', 'b', 'e', 'c', 'a'}
# intersection
print(x and y) # output: {'d', 'b', 'y', 'z', 'x'}
print(x & y) # output: {'b', 'd'}
i expected the outputs for union and intersection to be the same for each. how is it possible that they are not? can anyone explain?
You cannot override the functionality of logical and and or in python. So when you call:
>>> set([1, 2, 3]) or set([2, 3, 4])
{1, 2, 3}
It's treating it as logical or, which would evaluate the left side to boolean true and immediately stops evaluating and returns the left side. Similarly:
>>> set([1, 2, 3]) and set([2, 3, 4])
{2, 3, 4}
Is treated as a logical and, which would evaluate the left side to boolean True and then evaluate the right side to boolean True resulting in the right side being returned.
Logical and and or have no relationship to bitwise & and | in any language, python included.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With