Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of "and" with sets in Python

Tags:

python

set

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?

like image 373
yahiaelgamal Avatar asked Feb 05 '13 22:02

yahiaelgamal


People also ask

Is {} a set in Python?

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.).

What does set () in Python do?

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.

Is sets are mutable in Python?

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.


1 Answers

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.

like image 156
abarnert Avatar answered Sep 28 '22 14:09

abarnert