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.

Using XOR

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

Using not operator

You can use not operator as below

Using lambda expression

You can use lambda expression as below:

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.

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.

Output

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

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.

Output

Using bitwise operators

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

Output

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

Was this post helpful?

Leave a Reply

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