The Python Oracle

What does |= (ior) do in Python?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Magical Minnie Puzzles

--

Chapters
00:00 What Does |= (Ior) Do In Python?
00:12 Answer 1 Score 114
00:36 Answer 2 Score 10
00:50 Answer 3 Score 49
01:09 Answer 4 Score 53
01:16 Thank you

--

Full question
https://stackoverflow.com/questions/3929...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ANSWER 1

Score 114


In Python, and many other programming languages, | is the bitwise-OR operation. |= is to | as += is to +, i.e. a combination of operation and asignment.

So var |= value is short for var = var | value.

A common use case is to merge two sets:

>>> a = {1,2}; a |= {3,4}; print(a)
{1, 2, 3, 4}



ANSWER 2

Score 53


When used with sets it performs union operation.




ANSWER 3

Score 49


This is just an OR operation between the current variable and the other one. Being T=True and F=False, see the output graphically:

r s r|=s
T T T
T F T
F T T
F F F

For example:

>>> r=True
>>> r|=False
>>> r
True
>>> r=False
>>> r|=False
>>> r
False
>>> r|=True
>>> r
True



ANSWER 4

Score 10


It performs a binary bitwise OR of the left-hand and right-hand sides of the assignment, then stores the result in the left-hand variable.

http://docs.python.org/reference/expressions.html#binary-bitwise-operations