Skip to main content

How To Compare Python Two Lists

in this python tutorial, I’ll show you how to compare two python lists using different ways. We’ll use sort and compare and member method check two lists is identical or not.

We’ll compare the following ways to compare the list:

  • By == Operator
  • the set() method
  • The sort() function
  • The collection.counter() function

You can also checkout other python list tutorials:

How To Compare Two List in Python

Let’s discuss different ways in python to compare two lists.

Compare Operator

We can compare two lists using compare operator. You can compare the two lists using “==” operator, it returns True if all the elements in the lists are the same and in the same order.

a = [6, 5, 1, 2]
b = [6, 5, 1, 2]

print(a==b)

Output:

True

set() Method to compare two Lists

Python set() method manipulates the list into the set without taking care of the order of elements. We use the equal to operator (==) to compare the data items of the list.

a = [6, 5, 1, 2]
b = [6, 5, 1, 2]

l1 = set(a)  
l2 = set(b)  
  
if l1 == l2:  
    print("The a and b are equal")  
else:  
    print("The a and b are not equal")

Output:

The a and b are equal

sort() Method to compare two Lists

The python sort() function is used to sort the lists. The same list’s elements are the same index position it means; lists are equal.

a = [6, 5, 1, 2]
b = [6, 5, 1, 2]

a.sort()  
b.sort()  
  
if a == b:  
    print("The a and b are equal")  
else:  
    print("The a and b are not equal")

Output:

The a and b are equal

collection.counter() Method to compare two Lists

The Python collection module has counter() function, which is used to compare the lists. It stores the data in dictionary format : and counts the frequency of the list’s items.

import collections
a = [6, 5, 1, 2]
b = [6, 5, 1, 2] 
  
if collections.Counter(a) == collections.Counter(b): :  
    print("The a and b are equal")  
else:  
    print("The a and b are not equal")

Output:

The a and b are equal

Leave a Reply

Your email address will not be published. Required fields are marked *