What is numpy.logical_and() in Python?

Overview

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.

AND- Truth Table

Syntax


numpy.logical_and(p,
q,
/,
out=None,
*,
where=True,
casting='same_kind',
order='K',
dtype=None,
subok=True)

Parameters

  • 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.

Return value

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.

Example

In the code snippet below, we are computing logical AND between two scaler values, two boolean arrays, and conditions.

# import numpy library in program
import numpy as np
# invoking logical AND between two boolean values
print("p ^ q as boolean:", np.logical_and(31, 4))
# invoking logical AND between two boolean arrays
print("p ^ q as boolean arrays:", np.logical_and([True, True, False, True], [True, False, True, False]))
# creating a numpy array from 0 to 8
x = np.arange(8)
# print logical_and() results
print("p ^ q as conditions:", np.logical_and(x < 2, x > 5))

Explanation

  • Line 4: We calculate the logical AND between 31 and 4 that returns a true value because both of them are greater than zero.
  • Line 6: We evaluate the logical AND between two boolean lists.
  • Line 8–10: In line 8, 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.

Free Resources