Open In App

How to compare two lists in Python?

Last Updated : 12 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, there might be a situation where you might need to compare two lists which means checking if the lists are of the same length and if the elements of the lists are equal or not. Let us explore this with a simple example of comparing two lists.

Python
a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5]

# Compare the two lists directly to
#Check if they are identical
res = a == b
print(res)

Output
True

Let’s explore other methods to compare two lists in Python.

Using collections.Counter()

counter() function of the collections module is used to sort and store the list elements in the form of a dictionary which makes it easier to compare two lists.

Python
import collections  

a = [1, 2, 3, 4, 5]
b = [5, 4, 3, 2, 1]

# Counter creates a dictionary-like object 
res = collections.Counter(a) == collections.Counter(b)
print(res)

Output
True

Using sort()

Python list sort() function is used to sort a list in either ascending or descending order. It modifies the original list. Once the lists are sorted, they can be compared using the equality operator.

Python
a = [1, 2, 3, 4, 5]
b = [5, 4, 3, 2, 1]

# Using sort() to sort both lists in place.
res = a.sort() == b.sort()
print(res)

Output
True

Using sorted()

sorted() function does not modify the original list, instead creates a new list object. Once the lists are sorted, they can be compared using the equality operator.

Python
a = [1, 2, 3, 4, 5]
b = [5, 4, 3, 2, 1]

# Use the sorted() to create 
# sorted copies of the lists

# Sorts the first list
a_sorted = sorted(a)

# Sorts the second list
b_sorted = sorted(b)

res = a_sorted == b_sorted
print(res)

Output
True

Using set()

set() function is used to onvert an object into a set. This method to compare the lists is useful when the elements of the lists are unordered.

Python
a = [1, 2, 3, 4, 5]
b = [5, 4, 3, 2, 1]

# Convert the first list to a set
a_set = set(a)

# Convert the second list to a set
b_set = set(b)

res = a_set == b_set
print(res)

Output
True

Using all() and zip()

The all() function along with zip() pairs elements from both lists and checks if all corresponding elements are equal. This method works best if the lists are sorted.

Python
a = [1, 2, 3, 4, 5]
b = [5, 4, 3, 2, 1]

# Use the all() function along with zip() to 
#compare both lists element by element
res = all(x == y for x, y in zip(a, b))
print(res)

Output
False

Next Article

Similar Reads