How To Compare Elements Of Two Arrays In Python

In this tutorial, we will learn how to compare elements of two arrays in Python.

Comparing elements of two arrays is a common operation in any programming language and can be used in a variety of applications including comparing matrices, checking differences between lists, or finding items in common.

Here, we will use the built-in Python list and NumPy arrays for demonstration.

Steps

Follow the steps below to compare elements of two arrays in Python.

Step 1: Create two arrays

First, let’s create two Python lists named list1 and list2:

Additionally, we will create two NumPy arrays named array1 and array2. To do this, we will need to import the NumPy library first. If you don’t have NumPy installed, you can install it using the following pip command:

Now we import NumPy and create our arrays:

We have now created two Python lists and two NumPy arrays.

Step 2: Compare elements using a for loop

We can use a for loop to iterate over the elements of both lists and compare them.

Step 3: Compare elements using list comprehensions

A more concise way to achieve the same task is by using list comprehension. This will essentially create a new list with the common elements between the two lists:

Step 4: Compare elements of NumPy arrays using NumPy functions

Now, let’s do the same with NumPy arrays. Instead of using loops or list comprehensions, we can take advantage of the np.intersect1d() function, which automatically returns common elements between two arrays:

Output

Equal elements from lists: 4 4
Equal elements from lists: 5 5
Common elements between lists: [4, 5]
Common elements between NumPy arrays: [4 5]

Conclusion

In this tutorial, we learned how to compare elements of two arrays in Python using both Python lists and NumPy arrays. We demonstrated how to use for loops, list comprehensions, and NumPy functions to achieve this task. Comparing elements of arrays is a useful skill to have and is applicable to a wide range of scenarios in both data analysis and programming in general.