Convert 0 to 1 and 1 to 0 in Python

In this post, we will see how to convert 0 to 1 and 1 to 0 in Python.

Ways to convert 0 to 1 and 1 to 0 in Python

There are times when you need to convert 0 to 1 and 1 to 0.
For example: Flipping a bit in binary number.

There are lots of ways to convert 0 to 1 and 1 to 0 in Python. Let’s go through them.

Using Subtraction

This is one of easiest solution to swap 0 to 1 and vice versa. We can subtract i from 1 and assign it back to i.

i=0;
i = 1-i;
print(i); # Prints 1

Using XOR

You can use xor operator with 1 to convert 0 to 1 and 1 to 0 in Python.

i=0;
i = i^1;
print(i); # Prints 1

Using not operator

You can use not operator as below

i=1;
i = int(not(i))
print(i); # Prints 0

Using lambda expression

You can use lambda expression as below:

f = lambda val: 0 if val else 1;
print(f(0)); # print 1 
print(f(1)); # print 0 

Using addition and remainder operator

This is not better solution than subtraction or XOR.

You can add 1 to i and use % operator to find remainder and assign it back to i.

i = ( i + 1 ) % 2

Convert 1 to 0 and 0 to 1 in list

You can also apply above solution in a list to convert 0 to 1 and 1 to 0 in list in Python.

Here is an example to do it using xor operator.

list1 = [0,1,0,1,0];

print("List before flipping 0 and 1",list1);
list1 = [i^1 for i in list1] ;
#xor each element is the list

print("List after flipping 0 and 1",list1);

Output

Convert 1 to 0 and 0 to 1 in list

You can do using it using other solutions as well. You just need to change condition in above highlighted line.


#Using subtraction
list1 = [1-i for i in list1] ;

#Using not operator
list1 = [int((not i)) for i in list1] ;

Convert 1 to 0 and 0 to 1 in numpy array

There are multiple ways to convert 0 to 1 and 1 to 0 in numpy array.

Using where with bitwise xor

We can use np.where and applying bitwise xor in case value is either 1 or 0.

import numpy as np
a = np.array([[0,1,0,1], [1,0,0,1]])
print(a)

print("============")

a = np.where((a==0)|(a==1), a^1, a)

print(a)

Output

[[0 1 0 1]
 [1 0 0 1]]
============
[[1 0 1 0]
 [0 1 1 0]]

Using bitwise operators

We can make use of bitwise operators to convert 0 to 1 and 1 to 0 in Python.

import numpy as np
a = np.array([[0,1,0,1], [1,0,0,1]])
print(a)

print("============")

a = a^(a&1==a)

print(a)

Output

[[0 1 0 1]
 [1 0 0 1]]
============
[[1 0 1 0]
 [0 1 1 0]]

That’s all about how to convert 0 to 1 and 1 to 0 in python.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.