pyxx.arrays.is_array_equal#

pyxx.arrays.is_array_equal(item1: Array_or_Number_or_String, item2: Array_or_Number_or_String, *args: Array_or_Number_or_String, tol: float = 1e-16) bool#

Checks that arrays are equal in shape and content

Returns True if all arrays passed as arguments are of the same shape and all elements are equal within a given tolerance tol (for numeric elements) or exactly equal (for string elements), and returns False otherwise. Inputs can be lists, tuples, NumPy arrays, numbers, strings, or nested arrays composed of any of these types.

Parameters:
  • item1 (list or tuple or np.ndarray or Number or str) – First array to evaluate

  • item2 (list or tuple or np.ndarray or Number or str) – Second item to evaluate

  • *args (list or tuple or np.ndarray or Number or str, optional) – Any other arrays to be evaluated

  • tol (float, optional) – Maximum difference between numeric values to consider equivalent (default is 1e-16)

Returns:

Whether item1, item2, *args have the same shape, and all elements are equal within tolerance tol (for numeric elements) and exactly equal (for string elements)

Return type:

bool

Warning

  • The shape of the input arrays must be identical for the arrays to be considered equal. The shape of numbers is considered different from the shape of lists, so observe that 0 and [0] are not considered equal in shape.

  • By default, NumPy arrays are of homogeneous type. This means that, for instance, pyxx.arrays.is_array_equal(np.array([1, 'a']), [1, 'a']) evaluates to False (because the NumPy array is converted to all strings). To avoid this issue, it is possible to create NumPy arrays with the dtype=object argument and allow mixed types. For example, pyxx.arrays.is_array_equal(np.array([1, 'a'], dtype=object), [1, 'a']) evaluates to True.

Notes

Recursion Limit

Internally, is_array_equal() is a recursive function. It is possible that for extremely large nested arrays, Python’s recursion limit may be reached. If this occurs and it is necessary to compare such a large array, consider increasing the recursion limit using the sys.setrecursionlimit() function.

Purpose

One question that may arise is, why is this function necessary? NumPy already offers functions like numpy.array_equal(), numpy.isclose(), and numpy.allclose().

There are several main advantages of is_array_equal():

  • NumPy requires that arrays are numeric and are not “ragged” (sub-lists must all have the same length, recursively. For example, the array x = [[1,2,3], [1,2]] is “ragged” since len(x[0]) != len(x[1])). In contrast, is_array_equal() can compare arrays with a mix of strings, numbers, lists, and tuples, as well as “ragged” arrays.

  • The NumPy functions mentioned will typically throw an exception if the array sizes being compared differ, but is_array_equal() simply returns False in this case. This can eliminate the need to catch exceptions for certain applications.