Skip to content

Check if two lists are Equal Python | Example code

  • by

The easiest way is to use a list sort() method and == operator to Check if two lists are Equal in Python. If don’t want to sort the list then you can use the collections Counter() function.

Example check if two lists are Equal Python

Simple example code.

Using list.sort() and == operator

list1 = [1, 2, 4, 3, 5]
list2 = [1, 2, 4, 3, 5]

list1.sort()
list2.sort()

if list1 == list2:
    print("The lists are Equal")
else:
    print("The lists are not Equal")

Output:

Check if two lists are Equal Python

Using collections.Counter()

The Counter function from the collections module. It is used to find the number of occurrences of each item in the list. You have to import a collections module.

import collections

list1 = [1, 2, 4, 3, 5]
list2 = [1, 2, 4, 3, 5]

if collections.Counter(list1) == collections.Counter(list2):
    print("The lists are equal")
else:
    print("The lists are not equal")

Output: The lists are equal

Another way using NumPy

Using np.array_equal() to check if two lists are equal.

import numpy as np

list1 = [1, 2, 4, 3, 5]
list2 = [1, 2, 4, 3, 5]

result = np.array_equal(np.array(list1).sort(), np.array(list2).sort())

if result:
    print("The lists are equal")
else:
    print("The lists are not equal")

Output: The lists are equal

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

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading