Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

logical operators in python sets [duplicate]

Tags:

python

set

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?

like image 798
Nirvikalpa Samadhi Avatar asked Jul 22 '26 10:07

Nirvikalpa Samadhi


1 Answers

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.

like image 173
Matthew Story Avatar answered Jul 24 '26 00:07

Matthew Story



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!