Check if two lists are identical in Python


In python data analysis, we may come across situation when we need to compare two lists and find out if they are identical meaning having same elements or not.

Exmple

 Live Demo

listA = ['Mon','Tue','Wed','Thu']
listB = ['Mon','Wed','Tue','Thu']
# Given lists
print("Given listA: ",listA)
print("Given listB: ",listB)
# Sort the lists
listA.sort()
listB.sort()

# Check for equality
if listA == listB:
   print("Lists are identical")
else:
   print("Lists are not identical")

Output

Running the above code gives us the following result −

Given listA: ['Mon', 'Tue', 'Wed', 'Thu']
Given listB: ['Mon', 'Wed', 'Tue', 'Thu']
Lists are identical

With Counter

The Counter function from collections module can help us in finding the number of occurrences of each item in the list. In the below example we also take two duplicate elements. If the frequency of each element is equal in both the lists, we consider the lists to be identical.

Example

 Live Demo

import collections
listA = ['Mon','Tue','Wed','Tue']
listB = ['Mon','Wed','Tue','Tue']
# Given lists
print("Given listA: ",listA)
print("Given listB: ",listB)
# Check for equality
if collections.Counter(listA) == collections.Counter(listB):
   print("Lists are identical")
else:
   print("Lists are not identical")

# Checking again
listB = ['Mon','Wed','Wed','Tue']
print("Given listB: ",listB)

# Check for equality
if collections.Counter(listA) == collections.Counter(listB):
   print("Lists are identical")
else:
   print("Lists are not identical")

Output

Running the above code gives us the following result −

Given listA: ['Mon', 'Tue', 'Wed', 'Tue']
Given listB: ['Mon', 'Wed', 'Tue', 'Tue']
Lists are identical
Given listB: ['Mon', 'Wed', 'Wed', 'Tue']
Lists are not identical

Updated on: 13-May-2020

377 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements