The pipe symbol(|) in Python
The | symbol can have different interpretations in Python depending on the context in which it is used.
1.Union
When this operator is used with data structure such as dictionary or set, it performs a union operation and returns a set/dictionary containing
items from both initial data structures.
Let’s explore this example where we merge 2 dictionaries:
[*]snip
x = {"a":1,"b":2}
y = {"c":3,"d":4}
print(x|y)
[*]Output
{‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}
Note: If a key appears in both dictionary the key from the second dictionary is used:
[*]snip
{"a":1,"b":2} | {"a":2,"c":3}
[*]output
{‘a’: 2, ‘b’: 2, ‘c’: 3}
Let’s consider operation on set :
[*]snip
x = {1,2,3}
y = {1,2,4}
print(x|y)
[*]Output
{1, 2, 3, 4}
With this, we are able to create a set that contains all the items from both sets(Recall that set holds unique items)
We only combined two sets/dictionaries as show above, but there is no limitations to the number of sets/dictionaries that can be combined.
[*]snip
{1,2,3}|{4,5,6}|{7,8,9}
{'a':1} | {'b':2} | {'c':3}
[*]Output
{1, 2, 3, 4, 5, 6, 7, 8, 9}
{‘a’: 1, ‘b’: 2, ‘c’: 3}
2.Logical OR:
When | is used on boolean values(i.e. True and False), it performs a logical OR operation. OR returns True if either of the operands is True, and False otherwise.
[*]snip
True | True
False | True
False | False
[*]Output
True
True
False
The above is the same as using the logical ‘or’ operator as show below:
True or True
False or True
False or False
[*]Output
True
True
False
3. Bitwise OR:
When | is used on integer values, is performs a bitwise OR operation. The integers are converted to binary format and operations are performed on each bit and the results are then returned in decimal format. Bitwise OR returns 1 if either of the bit is 1 else 0.
[*]snip
12 | 7
[*]Output
15
Explanation
12 = 1100 (Binary format)
7 = 0111 (Binary format)
12|7 = 1111 (Binary)
int(‘1111’, 2) returns 15.
We used int(‘1111’, 2) to convert binary to decimal. (f”{12:b}”) converts an integer to binary.
Bitwise operators are mostly used in mathematical calculations. We can support it in our custom objects by overloading the operators.
Thanks for reading and feel free to explore my video collection on YouTube for more educational content. Don’t forget to subscribe to the channel to stay updated with future releases.