Some Useful Things About Tilde Operator in Python

In this article, we will learn about a tilde operator in python. Tilde operator is one of the types in Bitwise operator. ~ is a symbol that denotes a tilde operator in python. Look at this symbol. It is something different from others. We are not using these symbols the most. This operator is also known as complement operator or NOT operator. It returns the inversion of the binary code. If the binary code is 0, then it changes it as a one. Suppose the binary digit is one. It changes it to zero.

Tilde operator is a type of operator that reverses the binary of a given number. For example, if I give a=100100, the result of ~a is 011011. If we apply the same process to the decimal value 8, the value will be -9. Many of us amazing how it is happening. Let us learn it step by step below.

Steps to prove the complement of 8 is -9:

  • Find the binary value for 8. The value is 00001000.
  • Now we have to find the complement for the value 8. That is 11110111.
  • We got an answer for 8 is -9. First, we will find the binary code for 9 that is 00001001.
  • Now we find the 1’s complement for the value 9. The value is 11110110.
  • Next, we have to find the 2’s complement for the binary number 9.
  • To find the 2’s just add 1 to the 1’s complement.
  • Adding 1, the value is 11110111. This is the 2’s complement for 9.
  • 2’s complement is the negative form of the value.
  • Now we can see that the binary form of 8 and -9 is the same.
  • So, we are getting the value, -9.

Table for Tilde operator

First, we will see some tilde operations for positive values

Tilde operationBinary bit for valuesBit TransformationResult
~0 0000000011111111-1
~1 0000000111111110-2
~2 0000001011111101-3
~3 0000001111111100-4

Now let us move for negative values

Tilde operationBinary bit for valuesBit TransformationResult
~-111111111000000000
~-211111110000000011
~-311111101000000102
~-411111100000000113

Tilde operator in python array indexing

Generally, we are indexing a value in two types positive and negative indexing. Positive indexing starts from left to right, and the initial value is zero. Negative indexing starts from the end of the list or tuple, and the initial value is -1. But here, it is something different. If we give a value as ~0, the value will be written with a positional value -1. Because we already saw the table ~0 is -1.

Let us implement this in a python code

Code

lst=[1,3,4,5,7,5,9,0]
print(lst[~1])
print(lst[~0])
print(lst[~7])

Explanation

The value of ~1 is -2. So the value is 9. The value of ~0 is -1, so it returns 0. And the value of ~7 is -8. So it returns the first element.

Output

9
0
1

Invert a NumPy Boolean array using tilde operator

import numpy as np
print(np.bitwise_not is np.invert)
print(np.bitwise_not is not np.invert)

Explanation

Import a NumPy module. Check if a bitwise not operator is inverted or not.

Output

True
False

Check if it is invert or not using __invert__(self)

import operator
class tilde:
    def __invert__(self):
        print ("invert")
x = tilde()
~x

Explanation

Import an operator. Create a class named “tilde”. invert(self) is useful to check whether the given is invert or not. If the given operator contains a tilde symbol, then it returns the result as invert. Otherwise, it returns nothing.

Output

invert

Using Tilde operator in Pandas data frame

import pandas as pd
data_frame = pd.DataFrame([{'Name': 'Jack', 'Age': 22},
                   {'Name': 'Jim', 'Age': 24}])
print(data_frame)
print("\n")
print("-----**Using Tilde Operator to print the string that doesn't contains 'i'**----")
print("\n")
data_frame= data_frame[~data_frame['Name'].str.contains('i')]
print(data_frame)

Explanation

Import a panda library. Create a data frame with Name and age. Now print the data frame. Next using the tilde operator to print the string that doesn’t contain ‘i’. We know that the tilde operator inverts a result. So we are giving str.contains(‘i’). It will check if the name contains ‘i’ or not. If the string contains ‘i’, it will ignore that string.

Output

   Name  Age
0  Jack   22
1   Jim   24


-----**Using Tilde Operator to print the string that doesn't contains 'i'**----


   Name  Age
0  Jack   22

Using Tilde operator in Python to check palindrome

string=input("Enter a string: ")
for i in range(len(string)//2):
    if string[i] != string[~i]:
        print("Not Palindrome")
        break
    else:
        print("Palindrome")
        break

Explanation

Get a string from a user to check palindrome. Create a for loop to divide the string by 2. The condition is if string[i] is not equal to string[~i]. Then it returns it is not a palindrome. If it is equal, it will return it is a palindrome.

Output

Enter a string: MALAYALAM
Palindrome
Enter a string: WELCOME
Not Palindrome

Tilde operator in python to remove NAN

from numpy import NAN
import pandas as pd
matrix = pd.DataFrame([1,2,3,4,NAN],columns=['Number'], dtype='float64')
a=matrix['Number'][~matrix['Number'].isnull()]
print(a)

Explanation

Import numpy and pandas. Numpy is to import NAN, and pandas are useful to create a data frame. Create a matrix with a value NAN. Next using the ~ operator to remove the NAN value from the matrix.

Output

0    1.0
1    2.0
2    3.0
3    4.0
Name: Number, dtype: float64

1. Which symbol is used to denote the tilde operator in python?

~ is a symbol that is useful to denote the tilde operator in python.

2. What is the purpose of the tilde operator in python?

The tilde operator is useful to get the inverse of the given number.

Conclusion

Here we have learned about a tilde operator in python in a brief manner. Tilde operator in python is one of the types of bitwise operator. We hope this article is easy to understand. Solve the programs on your own.

If you have any doubts, do let us know in the comment section. We will clear your doubts. Learn with us:)

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments