What is logical_xor() in NumPy?
Overview
The logical_xor() method in NumPy is used to perform the element-wise logical exclusive OR operation. It returns a single boolean value or boolean ndarray.
The return value of a XOR operation is True between two values A and B when both input values are different. Otherwise, it returns False. Let's look at the truth table for XOR on two input values:
xor truth table
A | B | A⊕B |
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
Syntax
numpy.logical_xor(x1,x2,/,out=None,*,where=True,casting='same_kind',order='K',dtype=None,subok=True)
Signature
Parameters
x1, x2: Array-like objects are used to applylogical_xor. Ifx1andx2dimensions are not alike, they are broadcast to a standard shape.out: This is the location in memory used to store results. It can bendarrayor a tuple ofndarrayorNone.where: When a location becomes true, theoutarray is set toufunc.casting: The default value for this issame_kind, meaning that object casting will be the same asfloat64andfloat32.**kwargs: These are the keyword arguments.
Return value
It returns a single boolean value or ndarray of boolean type.
Example
In the code snippet below, we discuss different scenarios of the logical_xor() function where x1 and x2 can be either single boolean values or part of a boolean array. These values can be conditions where results are computed based on whether they're True or False.
# import numpy library in programimport numpy as np# invoking logical xor on two boolean valuesprint("x1 & x2 as boolean values: ", np.logical_xor(True, False))# invoking logical xor on two boolean arraysprint("x1 & x2 as boolean arrays: ", np.logical_xor([True, True, False, False], [True, False, True, False]))# creating a numpy array from 0 to 10x = np.arange(10)# print logical_xor() resultsprint("x1 & x2 are conditions: ", np.logical_xor(x < 1, x > 3))
Explanation
- Line 4: We calculate the logical XOR between two boolean values by calling
np.logical_xor(). - Line 6: We calculate the logical XOR between two boolean arrays of length
4by callingnp.logical_xor()with arrays as arguments. - Line 8–10: We calculate the logical XOR between two conditional values as
x1andx2by callingnp.logical_xor(). It returns a boolean array where each element of an arrayxsatisfies the inequalityx < 1andx > 3.