How do I toggle a boolean array in Python? How do I toggle a boolean array in Python? arrays arrays

How do I toggle a boolean array in Python?


Using not is still the best way. You just need a list comprehension to go with it:

>>> x = [True, True, True, True]>>> [not y for y in x][False, False, False, False]  >>> x = [False, True, True, False]>>> [not y for y in x][True, False, False, True]>>>

I'm pretty sure my first solution is what you wanted. However, if you want to alter the original array, you can do this:

>>> x = [True, True, True, True]>>> x[:] = [not y for y in x]>>> x[False, False, False, False]>>>


In pure python, with a list comprehension

>>> x = [True, False, False, True]>>> [not b for b in x][False, True, True, False]

Or, you may consider using numpy arrays for this functionality:

>>> x = np.array(x)>>> ~xarray([False,  True,  True, False], dtype=bool)


@iCodez's answer with list comprehension is more pythonic. I'll just add one other way of doing it:

>>> a = [True, True, True, True]>>> print map(lambda x: not x, a)[False, False, False, False]