What does this mean? (&)

Ridwan Yusuf
2 min readJan 29, 2023

--

In a previous post, we explained how the pipe (|) symbol can have different meanings depending on context in Python. This guide provides similar details but for the ampersand (&) symbol.

1.Intersection

When & is used on sets, it performs an intersection operation and returns a set that contains items that are present in both sets.
[*]snip

x =  {1,2,3,4} 
y = {2,6,8,9}
print(x & y)

[*]Output
{2}

2.Logical AND:

When & is used on boolean values(i.e. True and False), it performs a logical AND operation. AND returns True if both of the operands are True, and False otherwise
[*]snip

True & True
False & True
False & False

[*]Output
True
False
False

The above is the same as using the ‘and’ operator as show below:
[*]snip

True and True
False and True
False and False

[*]Output
True
False
False

3. Bitwise AND:

When & is used on integer values, is performs a bitwise AND operation. The integers are converted to binary format and operations are performed on each bit and the results are then returned in decimal format. Bitwise AND returns 1 if both the bits are 1 else 0.

[*]snip

12 & 7

[*]Output
4

Explanation:

12 = 1100 (Binary format)
7 = 0111 (Binary format)

12&7 = 0100 (Binary)
>>> int(‘0100’, 2)
4

We used int(‘0100’, 2) to convert binary to decimal. (f”{12:b}”) converts an integer to binary.

The bits are compared to attain a value of ‘0100’ which is later converted to decimal(4)

Thanks for reading and feel free to explore my video collection on YouTube for more educational content. Don’t forget to subscribe to the channel to stay updated with future releases.

--

--

Ridwan Yusuf

RidwanRay.com -I provide engineers with actionable tips and guides for immediate use