How to Compare Two Lists in Python
Learn how to compare two lists in Python using ==, set(), loops, and Counter.
Comparing two lists in Python is a common task. Maybe you want to check if two results are the same, or see if a list contains the same items as another. In this blog, we'll explore simple and beginner-friendly ways to solve the question: how to compare two lists in python?
Method 1: Use == to Check Exact Match
The easiest way to compare two lists is with the == operator. This checks if both the order and the values are the same.
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(list1 == list2) # True
If the order is different, it returns False:
list1 = [1, 2, 3]
list2 = [3, 2, 1]
print(list1 == list2) # False
Method 2: Use set() to Ignore Order
If you don't care about the order of items, you can use set() to compare contents only:
list1 = [1, 2, 3]
list2 = [3, 2, 1]
print(set(list1) == set(list2)) # True
⚠️ Warning: set() removes duplicates. So [1, 2, 2] and [1, 2] will be considered the same.
Method 3: Compare Elements One by One
You can write a small function to compare lists item by item. This is helpful if you need custom rules (e.g., case-insensitive comparison).
def compare_lists(l1, l2):
if len(l1) != len(l2):
return False
for a, b in zip(l1, l2):
if a != b:
return False
return True
print(compare_lists([1, 2, 3], [1, 2, 3])) # True
Method 4: Use collections.Counter
This is the most flexible method! It checks if the lists have the same elements and the same number of each.
from collections import Counter
list1 = [1, 2, 2, 3]
list2 = [2, 1, 2, 3]
print(Counter(list1) == Counter(list2)) # True
Counter turns lists into dictionaries that count how many times each item appears.
Summary
Method | Order Matters | Duplicates Matter | When to Use |
---|---|---|---|
== | ✅ Yes | ✅ Yes | When you want an exact match |
set() | ❌ No | ❌ No | When you only care about contents |
Element-by-element | ✅ Yes | ✅ Yes | When you need custom logic |
collections.Counter | ❌ No | ✅ Yes | When order doesn't matter but count does |
Further Reading
If you find this too cumbersome, you can also try our free online comparison tool to make data comparison quick and simple.