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?
Creating Python SetsA set is created by placing all the items (elements) inside curly braces {} , separated by comma, or by using the built-in set() function. It can have any number of items and they may be of different types (integer, float, tuple, string etc.).
Python | set() method set() method is used to convert any of the iterable to sequence of iterable elements with distinct elements, commonly called Set. Parameters : Any iterable sequence like list, tuple or dictionary. Returns : An empty set if no element is passed.
A set is mutable, i.e., we can remove or add elements to it. Set in python is similar to mathematical sets, and operations like intersection, union, symmetric difference, and more can be applied.
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 set
s (as in your example) and list
s (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.
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