yahiaelgamal
yahiaelgamal

Reputation: 174

Behavior of "and" with sets in Python

I know that if I want to get the intersection of two sets (or frozensets) I should use the 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 am just curious why? what does this and represent when used with lists?

Upvotes: 8

Views: 123

Answers (1)

abarnert
abarnert

Reputation: 365975

x and y just treats the whole x and y expressions as boolean values. If x is false, it returns x. Otherwise, it returns y. See the docs for details.

Both sets (as in your example) and lists (as in your question) are false if and only if they're empty. Again, see the docs for details.

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

Upvotes: 14

Related Questions