Python: practical uses for &=

Pete Fison
3 min readJul 27, 2023
Photo by Alexander Sinn on Unsplash

I learnt something new today and thought it might be interesting to other folks…

You might already be familiar with Bitwise operators, in which case you know that & is a binary AND operator. 1 & 1 is True (1) but all other combinations of 1s and 0s are False (0).

As a quick aside, and to illustrate its operation, this actually gives us a neat way of checking if an integer is odd (1) or even (0) since the last bit of an odd number is always going to be 1:

>>> for x in range(100):
... print(f"{x} is {'odd' if x & 1 else 'even'}")
...
0 is even
1 is odd
2 is even
3 is odd
4 is even # etc

If you’re familiar with Assignment (or ‘update’) operators like += you’ll know they’re a useful shorthand for performing an operation and then assigning the result back to the original object i.e. the one on the left hand side of the operator. &= works the same… It performs the binary AND operation and assigns the value back to the original object.

>>> a = 11
>>> a &= 1
>>> a
1
>>> a &= 0
>>> a
0
>>> type(a)
<class 'int'>

I’m not sure whether it’s by happy coincidence or design but the same syntax can be used to perform an AND operation on the elements of two sets and (thanks to Terry Davis for pointing this out in the…

--

--

Pete Fison

Experienced Python developer with a special interest in web scraping, data wrangling, ETL, NLP, and AI Prompt Engineering. Former IT Director & Video Producer.