Open In App

Check if Two Lists Have Same Elements regardless of Order - Python

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

We have multiple ways to check if two lists have the same elements, regardless of their order. The simplest way to check if two lists have the same elements is to sort both lists and then compare them. If both lists have the same elements in the same order after sorting, they are the same.

Python
def check_lists(a, b):
    # Sort both lists
    a.sort()
    b.sort()
    
    # Compare if sorted lists are the same
    return a == b

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

print(check_lists(a, b))  

Output
True

Using collections.Counter

A more efficient method is to use the Counter class from Python's collections module. It allows us to count the number of occurrences of each element in the lists. If the counts match, the lists are the same.

Python
from collections import Counter

def check_lists(a, b):
    # Use Counter to count elements in both lists
    return Counter(a) == Counter(b)

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

print(check_lists(a, b)) 

Output
True

Using a Dictionary

We can also use a dictionary to manually count the elements. This method is a bit more complex than the previous ones but still works well.

Python
def check_lists(a, b):
    # If the lengths of the lists are different, they cannot have the same elements
    if len(a) != len(b):
        return False

    # Create a dictionary to count occurrences of elements in list a
    count_a = {}
    for item in a:
        count_a[item] = count_a.get(item, 0) + 1

    # Check if the elements in list b match the counts in list a
    for item in b:
        if count_a.get(item, 0) == 0:
            return False
        count_a[item] -= 1

    return True

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

print(check_lists(a, b)) 
 
  

Output
True

Next Article

Similar Reads