Related Articles

# How to invert the elements of a boolean array in Python?

• Last Updated : 17 Dec, 2020

Given a boolean array the task here is to invert its elements. A boolean array is an array which contains only boolean values like True or False, 1 or 0.

Input : A=[true , true , false]

Output: A= [false , false , true]

Input: A=[0,1,0,1]

Output: A=[1,0,1,0]

Method 1:

You can use simple if else method to invert the array. In the implementation shown below method you just need to check the value of each index in array if the value is true change it to false else change it to true. This is one of the simplest method you can use to invert elements of a boolean array.

Program:

## Python3

 `a1 ``=` `((``0``, ``1``, ``0``, ``1``)) ` `a ``=` `list``(a1) ` ` `  `for` `x ``in` `range``(``len``(a)): ` `    ``if``(a[x]): ` `        ``a[x] ``=` `0` `    ``else``: ` `        ``a[x] ``=` `1` ` `  `print``(a) `

Output:

`[1, 0, 1, 0]`

Method 2:

You can also use an inbuilt function of numpy library to invert the whole array.

Syntax:

`np.invert(boolean[] a)`

Program:

## Python

 `import` `numpy as np ` ` `  ` `  `a ``=` `np.array((``True``, ``True``, ``False``, ``True``, ``False``)) ` `b ``=` `np.invert(a) ` `print``(b) `

Output:

`[False False  True False  True]`

Method 3:

We can also use the Tilde operator (~) also known as bitwise negation operator in computing to invert the given array. It takes the number n as binary number and “flips” all  0 bits to 1 and 1 to 0 to obtain the complement binary number.

So in the boolean array for True or 1 it will result in -2 and for False or 0 it will result as  -1. And again by using if..else we can convert the array into or required answer.

Program:

## Python3

 `a1 ``=` `((``0``, ``1``, ``0``, ``1``)) ` `a ``=` `list``(a1) ` ` `  `for` `x ``in` `range``(``len``(a)): ` `    ``# using Tilde operator(~) ` `    ``a[x] ``=` `~a[x] ` ` `  `print``(a) `

Output:

`[-1, -2, -1, -2]`

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :