# Python - How To Check List Equality in Python

ID : 290

viewed : 244

Tags : PythonPython List  92

In this tutorial, we will look into various methods of checking if the two lists are equal in Python. For the two lists to be equal, each element of the first list should be equal to the second list’s corresponding element. If the two lists have the same elements, but the sequence is not the same, they will not be considered equal or identical lists.

Suppose we have `listA = [4,7,2,9,1]`, `listA` would be equal to `listB` if and only if all elements of `listB` are identical to `listA`, i.e. `listB = [4,7,2,9,1]`. We can check whether the two lists are equal in Python using the below-explained methods.

## Check Equality of Lists in Python Using the Equality `==` Operator

A straightforward way to check the equality of the two lists in Python is by using the equality `==` operator. When the equality `==` is used on the list type in Python, it returns `True` if the lists are equal and `False` if they are not.

The below example code demonstrates how to use the equality `==` operator to check if the two lists are equal in Python.

``a = [4,7,3,5,8] b = [4,7,3,5,8] c = [1,7,3,5,2]  print(a == b) print(a == c) ``

Output:

``True False ``

Now, let us look into the scenario where we want to get element-wise results. Suppose we want to check which corresponding elements of the second array are equal and which are not equal.

For this, we first need to convert the lists to `NumPy` array using the `np.array()` method and then use the equality `==` operator, which will return `True` or `False` for each element.

The below example code demonstrates how to check if the elements of two lists are equal or not in Python.

``import numpy as np  a = [4,7,3,5,8] b = [4,7,3,5,8] c = [1,7,3,5,2]  print((np.array(a) == np.array(b))) print((np.array(a) == np.array(c))) ``

Output:

``[ True  True  True  True  True] [False  True  True  True False] ``

## Check Equality of Arrays in Python Using the Equality `==` Operator and the `numpy.all()` Method

In many cases, we use the `NumPy` arrays for different tasks. If we use the equality `==` operator to check the equality, we will get the element-wise result, as shown in the above example code.

Therefore, to check the equality of the `NumPy` arrays in Python, the `numpy.all()` method has to be used to check the arrays’ equality. The `np.all()` method returns `True` if the elements along the given axis evaluate to `True` and returns `False` otherwise.

The below example code demonstrates how to check whether the two arrays are equal or not in Python.

``import numpy as np  a = np.array([1,6,4,8,3]) b = np.array([1,6,4,8,3]) c = np.array([1,4,8,2,3])  print((a == b).all()) print((a == c).all()) ``

Output:

``True False ``