How to invert the elements of a boolean array in Python?
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]
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
Output: A= [false , false , true]
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.
[1, 0, 1, 0]
You can also use an inbuilt function of numpy library to invert the whole array.
[False False True False True]
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.
[-1, -2, -1, -2]