Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to invert the elements of a boolean array in Python?
Boolean array inversion is a common operation when working with data that contains True/False values. Python offers several approaches to invert boolean arrays using NumPy functions like np.invert(), the bitwise operator ~, or np.logical_not().
Using NumPy's invert() Function
The np.invert() function performs bitwise NOT operation on boolean arrays ?
import numpy as np
# Create a boolean array
covid_negative = np.array([True, False, True, False, True])
print("Original array:", covid_negative)
# Invert using np.invert()
covid_positive = np.invert(covid_negative)
print("Inverted array:", covid_positive)
Original array: [ True False True False True] Inverted array: [False True False True False]
Using the Bitwise NOT Operator (~)
The tilde operator ~ provides a concise way to invert boolean arrays ?
import numpy as np
# Create a boolean array
status = np.array([True, False, True, False])
print("Original:", status)
# Invert using ~ operator
inverted_status = ~status
print("Inverted:", inverted_status)
Original: [ True False True False] Inverted: [False True False True]
Using NumPy's logical_not() Function
The np.logical_not() function is specifically designed for logical operations ?
import numpy as np
# Create a boolean array
test_results = np.array([True, True, False, True, False])
print("Test results:", test_results)
# Invert using logical_not()
failed_tests = np.logical_not(test_results)
print("Failed tests:", failed_tests)
Test results: [ True True False True False] Failed tests: [False False True False True]
Without Using NumPy
You can invert boolean values using Python's built-in not operator with list comprehension ?
# Using regular Python list
original = [True, False, True, False, True]
print("Original list:", original)
# Invert using list comprehension
inverted = [not x for x in original]
print("Inverted list:", inverted)
# Using map function with lambda
inverted_map = list(map(lambda x: not x, original))
print("Using map:", inverted_map)
Original list: [True, False, True, False, True] Inverted list: [False, True, False, True, False] Using map: [False, True, False, True, False]
Comparison
| Method | Best For | Performance |
|---|---|---|
np.invert() |
Large arrays | Fast |
~ operator |
Concise syntax | Fast |
np.logical_not() |
Clear intent | Fast |
| List comprehension | Small lists, no NumPy | Slower |
Conclusion
For NumPy arrays, use np.invert(), ~, or np.logical_not() for efficient boolean inversion. For regular Python lists without NumPy, use list comprehension with the not operator.
