We use the logical_and()
function from the Numpy library to compute logical AND
between two boolean values or ndarrays. The AND operation between p
& q
is true when both inputs are true. Otherwise, it returns false. In mathematical terms, the AND operation is represented as ^
. Here, we have a truth table for the AND gate.
numpy.logical_and(p,q,/,out=None,*,where=True,casting='same_kind',order='K',dtype=None,subok=True)
p,q
: These are array-like objects and we use them to apply the logical AND. If p
and q
dimensions are not alike i.e p.shape!= q.shape
then they are broadcasted to a standard shape as out
.out
: We use this as the location in memory to store results. It can be ndarray or tuple of ndarray or None.where
: When a location becomes true, the out
array is set to ufunc.casting
: It has the following possible values 'safe'
, 'same_kind'
, 'unsafe
, 'no'
, 'equiv'
. Default= 'same_kind'
that means object casting will be the same as float32 and float64.**kwargs
: These are the additional keyword arguments.It returns either ndarray or bool value. We determine the shape by applying the AND
operation to p
& q
; the shape is determined by broadcasting.
In the code snippet below, we are computing logical AND
between two scaler values, two boolean arrays, and conditions.
# import numpy library in programimport numpy as np# invoking logical AND between two boolean valuesprint("p ^ q as boolean:", np.logical_and(31, 4))# invoking logical AND between two boolean arraysprint("p ^ q as boolean arrays:", np.logical_and([True, True, False, True], [True, False, True, False]))# creating a numpy array from 0 to 8x = np.arange(8)# print logical_and() resultsprint("p ^ q as conditions:", np.logical_and(x < 2, x > 5))
AND
between 31 and 4 that returns a true value because both of them are greater than zero.AND
between two boolean lists.np.arange(8)
will create a NumPy array from 0 to 7. While in line 10, logical_and(x < 2, x > 5)
will return a boolean array after confirming a number that satisfies x < 2
, x > 5
.