I'm trying to crack a code that's been passed to me.
In one of the code operations we have the following operation:
A = B & C
When I print A, B and C:
print (A)
print (B)
print (C)
I get as output something like the following (character strings are invented):
frozenset({('234', 'bla bla bla'),('8', 'blo blo blo'),('1','oe oe')})
frozenset({('2', 'bla'),('9', 'blo'),('11','oe')})
frozenset({('23', 'ddd'),('3', 'brr'),('44','e')})
My question is: What role does the ampersand have in the operation? What are you doing?
In the context in which it is used in your case, the operator
&
performs the mathematical operation known as set intersection .A set or set is a collection of objects without repetition and disordered. They are implemented using hash tables so the objects must be "hashable" as with
str
,tuple
,frozenset
,int
orfloat
(mutable objects like sets themselves or lists are not allowed as elements of a set as they are not "hashable"). Among its advantages are great efficiency in searches or the possibility of performing operations such as intersection (A & B
), union (A | B
), difference (A - B
) or symmetric difference (A ^ B
).If we have two sets
A
andB
,A & B
it returns another set that only contains the elements that are present in both at the same time , discarding those that are present in only one:It is equivalent to using the
set.intersection()
.It works identically for
frozenset
what is just an immutable set (and what if it can be an element of anotherset
orfrozenset
being "hashable"):As you can see, the returned set only includes those elements (in this case tuples) that are present both in
A
and inB
at the same time.In other contexts, for example applied to integers, it is a bitwise operator, the binary and (bitwise and). It will return, for each bit of the output, 1 if both bits are 1 and 0 otherwise:
As you can see, it takes each pair of bits of the operands and only returns 1 if both bits are also 1: