Use of tilde operator in Python

In this tutorial, you will learn the use of the tilde(~) operator in Python. The tilde(~) operator is a part of the bitwise operators in Python. The tilde(~) is also called a complement or invert operator.

The tilde(~) operator takes a one-bit operand and returns its complement.

 

Example 1:
>>>a=5
>>>print(~a)
-6

Example 2:
>>>a=-5
>>>print(~a)
4

Explanation:

In the first example, after printing the tilde of “a” the output is -6. In the second example, after printing the tilde of “a” the output is 4. It may seem like we are adding and subtracting with the help of the tilde operator, but it works based on the bits, not numbers, as the name suggests – it’s a bitwise operator.

Let’s take the above example 1:

a=5 can be written as

0 0 0 0 0 1 0 1

~a can be written as

1 1 1 1 1 0 1 0

Since the unary bit is activated (the first bit is one) convert it to 2’s compliment

1's compliment: 0 0 0 0 0 1 0 1
after adding one bit: 0 0 0 0 0 1 1 0

So the final answer is -6. Here minus is because we have done 2’s compliment.

As we can see from the examples, the output is based on the formula -x-1, where x represents the integer value provided by the user.

Here is the code for the proof for the tilde operator:

a=42
print(bin(a)) #print the value in bits
print(~a) #print the tilde value
print(bin(~a)) #print the tilde value in bits
Output:
0b101010
-43
-0b101011


The tilde is used in arrays, where the array can be accessed in reverse order i.e. ~0 represents its value as -1. we can display the array in reverse order by using negative indexing. So, here starting point of the array index is taken from the back of the array.

Leave a Reply

Your email address will not be published. Required fields are marked *