Compare two Arrays in Python | Example code

Simple use equality operator to compare two Arrays in Python.

a == b

Example compare two Arrays in Python

Simple example code.

a = [1, 2, 3]
b = ['a', 'b']
c = [1, 2, 3, 4]
d = [1, 2, 3]

print(a == b)
print(a == c)
print(a == d)

Output:

Compare two Arrays in Python

How to compare two NumPy arrays?

We generally use the equality == operator to compare two NumPy arrays to generate a new array object. Call the all() with to check if the two NumPy arrays are equivalent.

import numpy as np

a1 = np.array([[1, 2], [3, 4]])
a2 = np.array([[1, 2], [3, 4]])

comparison = a1 == a2
equal_arrays = comparison.all()

print(equal_arrays)

Output: True

Examples less than and equal to operators to compare Arrays

import numpy as np

a = np.array([1, 2, 3])
b = np.array([2, 4, 8])

print("a > b")
print(np.greater(a, b))

print("a >= b")
print(np.greater_equal(a, b))

print("a < b")
print(np.less(a, b))

print("a <= b")
print(np.less_equal(a, b))

Output:

a > b
[False False False]
a >= b
[False False False]
a < b
[ True True True]
a <= b
[ True True True]

Note: Python doesn’t have Arrays. It’s called a List in Python.

Do comment if you have any doubts and suggestions on this Python Array topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.