What does the &= operator do in Python?


The += operator is syntactic sugar for object.__iand__() function. From the python docs:

These methods are called to implement the augmented arithmetic assignments (+=, -=, *=, @=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self).

Example

So when you do something like −

a = 6 # 110 in binary
b = 5 # 101 in binary
a &= b # a changes to and of 110 and 101, ie, 100, ie, 4
print(a)

Output

This will give the output −

15

a is being modified in place here. You can read more about such operators on https://docs.python.org/3/reference/datamodel.html#object.__iand__.

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 05-Mar-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements