Tilde (~) Operator in Python

What is the Meaning of the Tilde Operator ~ in Python?

Python’s Tilde ~n operator is the bitwise negation operator: it takes the number n as binary number and “flips” all bits 0 to 1 and 1 to 0 to obtain the complement binary number. For example, the tilde operation ~1 becomes 0 and ~0 becomes 1 and ~101 becomes 010.

But be careful because the integer value 0 is represented by many bits. For example, if you have the integer 0 represented by eight bits (one byte) 0000 0000, the tilde operation ~0000 0000 results in the value 1111 1111 which is the integer value -1.

The general formula to calculate the tilde operation ~i on an integer value i is ~i=-i-1.

Have a look at the Python code where you convert the integer 42 with binary representation 0010 1010 to the complement -0010 1011:

>>> a = 42
>>> bin(a)
'0b101010'
>>> ~a
-43
>>> bin(~a)
'-0b101011'

Try it yourself in our interactive Python shell:

Can you guess the output of the code in the interactive shell? Guess first, then check if you guessed right!

If you struggle understanding how the tilde operator works on integers, have a look at the following table:

Tilde Python Table

Here’s a table showing the results of various tilde operations on positive integer values.

Tilde OperationBit TransformationInteger Result
~0~00000000-->11111111-1
~1~00000001-->11111110-2
~2~00000010-->11111101-3
~3~00000011-->11111100-4
~4~00000100-->11111011-5
~5~00000101-->11111010-6
~6~00000110-->11111001-7
~7~00000111-->11111000-8
~8~00001000-->11110111-9
~9~00001001-->11110110-10
~10~00001010-->11110101-11
~11~00001011-->11110100-12

Here’s a table showing the results of various tilde operations on negative integer values.

Tilde OperationBit TransformationInteger Result
~0~00000000-->11111111-1
~-1~11111111-->000000000
~-2~11111110-->000000011
~-3~11111101-->000000102
~-4~11111100-->000000113
~-5~11111011-->000001004
~-6~11111010-->000001015
~-7~11111001-->000001106
~-8~11111000-->000001117
~-9~11110111-->000010008
~-10~11110110-->000010019
~-11~11110101-->0000101010

The general formula to calculate the tilde operation ~i is ~i=-i-1.

So what’s the use of the Tilde operator?

Tilde Python Array

You can use the tilde operator in Python when indexing list elements.

You may already know the negative indexing scheme in Python where you can access the last element of a Python list lst with lst[-1] and the second last element with lst[-2].

But this may feel unnatural to you because negative array indexing starts with -1 and you’re used to positive indexing that starts with 0. And here’s how the tilde operator comes into play: Use the tilde operator to transform your positive indices into negative indices as ~0=-1 and ~1=-2 and so on.

Here’s a graphical representation:

And here’s the code example:

>>> lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> lst[-10]
0
>>> lst[~9]
0
>>> lst[-1]
9
>>> lst[~0]
9

You can see that this may lead to more intuitive indexing for some people.

Tilde Python Pandas

Sometimes, you’ll see the tilde operator in a Pandas DataFrame for indexing. Here’s an example:

import pandas as pd

# Create a DataFrame
df = pd.DataFrame([{'User': 'Alice', 'Age': 22},
                   {'User': 'Bob', 'Age': 24}])
print(df)
'''
    User  Age
0  Alice   22
1    Bob   24
'''

# Use Tilde to access all lines where user doesn't contain 'A'
df = df[~df['User'].str.contains('A')]
print(df)
'''
  User  Age
1  Bob   24
'''

The tilde operator in Pandas negates the Boolean values in the DataFrame: True becomes False and False becomes True.

You can see this in action when printing the result of different operations:

This is the original DataFrame in the code:

print(df)
'''
    User  Age
0  Alice   22
1    Bob   24
'''

Now apply the contains operation to find all user names that contain the character 'A'.

print(df['User'].str.contains('A'))
'''
0     True
1    False
Name: User, dtype: bool
'''

The result is a DataFrame with Boolean values that indicate whether a user contains the character 'A' or not.

Let’s apply the Tilde operator to the result:

print(~df['User'].str.contains('A'))
'''
0    False
1     True
Name: User, dtype: bool
'''

Now, we use this DataFrame to access only those rows with users that don’t contain the character 'A'.

df = df[~df['User'].str.contains('A')]
print(df)
'''
  User  Age
1  Bob   24
'''

Let’s have a look at some related questions.

Tilde Python Path

If you are having trouble understanding the use of tildes (~) in your path when using the os.makedirs() method in Python, you are not alone. It can be confusing to use the tilde to indicate a home directory. Fortunately, there is an easy way to handle this issue.

When you are creating a directory in your home directory with os.makedirs(), you will need to expand the tilde manually. To do this, you can use the os.path.expanduser command.

For example:

my_dir = os.path.expanduser('~/some_dir')

This will ensure that your directory is created in the home directory, regardless of what is indicated by the tilde.

It is important to note that Python does not recognize the tilde as a shortcut for the home directory and it is best to avoid using it.

Additionally, it is possible to access a file or directory named “~” in the current directory even when tilde expansion is occurring, using the “./~” notation. This is because tilde expansion only occurs at the start of a file name.

Tilde Python Use – Example Palindrome

The following code uses the tilde operator ~ to determine if a given string x is a palindrome:

def check_palindrome(x):
    for i in range(len(x)//2):
        if x[i] != x[~i]:
            return False
    return True

print(check_palindrome('racecar'))
# True

print(check_palindrome('hello world'))
# False

This code checks if a given string is a palindrome.

The function takes in a string (x) as the argument. It then uses a for loop to iterate through the string up to the half-length of the string.

Within the loop, it checks if the character at the current index (i) is the same as the character at the index equivalent to the index length minus the current index (e.g., for a string of length 5, the 5th index is 0 minus the current index).

  • If the characters are not the same, the function returns False, otherwise it continues looping until the end of the string.
  • If all characters in the string are the same, the function returns True.

The two print statements then print whether the given strings ('racecar' and 'hello world') are palindromes or not.

👉 Recommended Tutorial: Python Palindrome Checker

Python Unary Tilde

The Python Tilde Operator (~) is a unary operator that performs bitwise inversion. It reverses all the bits in a given number, all ones become zeros and all zeros become ones. The Python Tilde Operator is a unary operator because it takes only one operand (number) and performs an inversion on it.

>>> ~0
-1
>>> ~1
-2
>>> ~2
-3

Python Tilde Index

You can use the Python tilde operator ~ to invert the index of the given string. The tilde operator ~i is used to invert the index so that the last i+1 characters of the string are returned.

text = 'Hello World'
last_four = text[~3:]

print(last_four)
# Output: orld

In this example, the tilde operator is applied to the index 3, which results in an index of -4. Therefore, the last four characters of the string (starting from the fourth character) are returned in the variable last_four.

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Programming Humor