Yariv
Yariv

Reputation: 13321

Numpy xor-reduce an array

How to xor all elements of a boolean numpy array using vectorized methods: i.e., a_1 xor a_2 xor ... xor a_n?

Upvotes: 7

Views: 4588

Answers (2)

seberg
seberg

Reputation: 8975

I would prefer using the xor ufunc I think, which is bitwise_xor (or logical_xor):

np.bitwise_xor.reduce(a)

or:

np.logical_xor.reduce(a)

One advantage is, you don't get bogus stuff for floats.

Upvotes: 13

ecatmur
ecatmur

Reputation: 157454

It's probably most efficient to just use sum:

np.sum(arr) % 2

Upvotes: 3

Related Questions