Open In App

Different ways to Invert the Binary bits in Python

Last Updated : 21 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We know how binary value for numbers look like. For example, the binary value for 10 (Number Ten) is 1010 (binary value).

Sometimes it is required to inverse the bits i.e., 0's to 1's ( zeros to ones) and 1's to 0's (ones to zeros). Here are there few ways by which we can inverse the bits in Python.

Using Loops

You can iterate through each bit of the binary string and manually flip 0 to 1 and 1 to 0.

Python
bit_s = '1010'
inverse_s = ''

for i in bit_s:
    if i == '0':
        inverse_s += '1'
    else:
        inverse_s += '0'
        
print("Inversed string is ", inverse_s)

Output
Inversed string is  0101

Using Dictionary

Dictionaries provide fast access to key-value pairs (O(1) time complexity). You can use a dictionary to map '0' to '1' and '1' to '0'.

Python
b_dict = {'0': '1', '1': '0'}
bit_s = '1010'
inverse_s = ''

for i in bit_s:
    inverse_s += b_dict[i]
    
print("Inversed string is", inverse_s)

Output
Inversed string is 0101

Explanation: dictionary b_dict maps 0 to 1 and 1 to 0.

Using List comprehension

List comprehension allows you to achieve the same result in a more compact and Pythonic way. The ternary operator can be used to conditionally replace 0 with 1 and 1 with 0.

Python
bit_s = '1010'

inverse_s = ''.join(['1' if i == '0' else '0' for i in bit_s])

print("Inversed string is", inverse_s)

Output
Inversed string is 0101

Explanation:

  • List comprehension is used to iterate over the binary string and apply the ternary operator for flipping each bit.
  • ''.join() method is used to convert the list of flipped bits back into a string.

Using the replace() Method

You can use the string replace() method to replace 1 with 2, then 0 with 1, and finally, 2 with 0. This method can be a bit tricky but still effective.

Python
bit_s = '1010'

# Replace "1" with "2"
inv_s = bit_s.replace('1', '2')

# Replace "0" with "1"
inv_s = inv_s.replace('0', '1')

# Replace "2" with "0"
inv_s = inv_s.replace('2', '0')

print("Inversed string is", inv_s)

Output
Inversed string is 0101

Explanation: This method leverages replace() to modify the bits step by step. It is a bit less efficient but still works.

Using bit-wise XOR operator

XOR operator is a powerful tool for flipping bits. XOR returns 1 if one of the bits is 1 and the other is 0. This is particularly useful for inverting bits.

Python
bit_s = '1010'

# Convert binary string into an integer
temp = int(bit_s, 2)

# XOR with 2^(n+1) - 1 to invert bits
inv_s = temp ^ (2 ** (len(bit_s)) - 1)

# Convert the result back to binary and strip the '0b' prefix
res = bin(inv_s)[2:]

print("Inversed string is", res)

Output
Inversed string is 101

Next Article
Article Tags :
Practice Tags :

Similar Reads