Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
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
Advertisements