Python Comparing Arrays

We can use the relational operators >, >=, <, <=, == and != to compare the arrays of same size. These operators compare the corresponding elements of the arrays and return another array with Boolean type values. It means the resultant array contains elements which are True or False.

A Python program to compare two arrays and display the resultant Boolean type array.


The any() function can be used to determine if any one element of the array is True.

The all() function can be used to determine whether all the elements in the array are True. The any() and all() functions return either True or False.


Python program to know the effects of any() and all() functions.


The functions logical_and(), logical_or() and logical_not() are useful to get the Boolean array as a result of comparing the compound condition.

The where() function can be used to create a new array based on whether a given condition is True or False. The syntax of the where() function is:

array = where(condition, expression1, expression2)

If the ‘condition’ is true, ‘expression1’ is executed and the result is stored into the array, else ‘expression2’ is executed and its result is stored into the array. For example,

a = array([10, 21, 30, 41, 50], int)

c = where(a%2==0, a, 0)

The new array ‘c’ contains elements from ‘a’ based on the condition a%2==0. This condition is applied to each element of the array ‘a’ and if it is True, the element of ‘a’ is stored into ‘c’ else ‘0’ is stored into c. Hence the array ‘c’ looks like this:

[10 0 30 0 50].


Python program to compare the corresponding elements of two arrays and retrieve the biggest elements.

The nonzero() function is useful to know the positions of elements which are non zero. This function returns an array that contains the indexes of the elements of the array which are not equal to zero. For example,

a = array([1, 2, 0, -1, 0, 6], int)

In the preceding array, the elements which are non zero are: 1, 2, -1 and 6. Their positions or indexes are: 0, 1, 3, 5. These indexes can be retrieved into another array ‘c’ as:

c = nonzero(a)