-1

I have been doing codewars challenges recently and stumbled across this: using the pipe symbol to add two items. I tried this in my python environment and am curious as to what this does and how this is different than just the + symbol.

print(5 | 2)

This of course outputs to 7. In the codewars problem I was looking at, one of the solutions used this to add two sets together. What does this mean?

martineau
  • 119,623
  • 25
  • 170
  • 301
Luke Fisher
  • 37
  • 1
  • 6

1 Answers1

3

| is a bitwise OR. In your example, it happens that:

0101
0010 |
---
0111

which is 7 in binary.

If you to calculate, for example, 5 | 9. you'll get 13, and not 14, since | is NOT +.

Side note: If you're applying | to two numbers that their bitwise AND returns 0, then the addition and the bitwise OR returns the same result.

In the case of 2 and 5, 2 & 5 = 0, so + and | returns the same result.

Maroun
  • 94,125
  • 30
  • 188
  • 241
  • Worth noting this behavior is also what was going on with the sets in the mentioned codewars problem. E.g. `{1,2} | {3} == {1,2,3}` – 0x263A Dec 10 '21 at 17:59