Python

What does the |= operator mean in Python?

March 26, 2022

What does the |= operator mean in Python?

In this article we will learn what the |= operator means in Python, and also how we can use it in our software.

|= operator thumb

What’s up programmer, ok? Let’s learn more about Python!

Usually when we have an operator next to =, it will execute a mathematical operation on some variable

For example:

x += y – adds the value of x to y;

x -= y – subtracts the value of y in x;

And we can represent this same operation explicitly:

x = x + y

x = x – y

So with the |, also called a pipe, it’s no different

But here we will have a binary operation being performed, that is, an operation performed bit by bit

And if we have an operation:

x |= y

It equates to:

x = x | and

That is, this operator is also known as OR

See this operation to fully understand:

a = 10
b = 12

print("{0:b}".format(a))
print("{0:b}".format(b))

a |= b
print(a)
print("{0:b}".format(14))

Here we have a a |= b, where a in binary is 1010 (10) and b in binary is (1100), adding this bit by bit we will have 1110 which is equivalent to 14

See also the output of the prints:

1010
1100
14
1110

That is, when we have a 1 and a 0, the 1 prevails, this causes the binary to change the value, consequently changing the value of the final result of the operation

Conclusion

In this article we learned how to use the |= operator in Python

Basically it’s a bitwise operation between left and right values

So if we have: a |= b, the operation performed will be: a = a | B

The forward slash “|” is also known as the OR operator.

Want to learn more about Python? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x