Python and Set Behavior

I know that if I want to get the intersection of two sets (or freezons), I must use ampersand & . Out of curiosity, I tried to use the word "and"

 a = set([1,2,3]) b = set([3,4,5]) print(a and b) #prints set([3,4,5]) 

I'm just wondering why? what does this mean and when used with lists?

+8
python set
source share
1 answer

x and y simply treats all the expressions x and y as logical values. If x is false, it returns x . Otherwise, y returned. See documents for more details.

Both set (as in your example) and list (as in your question) are false if and only if they are empty. Again, see the docs for details.

So x and y will return x if it is empty, and y otherwise.

+14
source share

All Articles