How do you check if two lists are equal in Python?
Posted by LeoRobs
Last Updated: August 25, 2024
Checking if two lists are equal in Python is straightforward. List equality is determined by comparing both the length and the contents of the lists. Here are effective methods to achieve this:
Method 1: Using the Equality Operator (==)
The simplest way to check if two lists are equal is by using the equality operator (==). This operator checks if both lists have the same elements in the same order.
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = [3, 2, 1]

# Check if list1 is equal to list2
are_equal_1 = list1 == list2  # True

# Check if list1 is equal to list3
are_equal_2 = list1 == list3  # False
Method 2: Using the all() Function with a Generator Expression
If a custom comparison is needed, or if you want to check for equality based on specific conditions, you can use the all() function in combination with a generator expression.
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = [1, 2, 4]

# Custom comparison using all()
are_equal_custom_1 = all(a == b for a, b in zip(list1, list2))  # True
are_equal_custom_2 = all(a == b for a, b in zip(list1, list3))  # False
Method 3: Using the set() Function
If the order of elements is not important and you want to check for equality based solely on the presence of items, you can convert the lists to sets. Note that this method will not account for duplicate elements.
list1 = [1, 2, 2, 3]
list2 = [3, 2, 1, 2]
list3 = [1, 2, 3]

are_equal_set_1 = set(list1) == set(list2)  # True
are_equal_set_2 = set(list1) == set(list3)  # True
Method 4: Using a Loop
Implementing a for-loop for more complex comparison scenarios can also work:
list1 = [1, 2, 3]
list2 = [1, 2, 3]

def lists_are_equal(lst1, lst2):
    if len(lst1) != len(lst2):
        return False
    for a, b in zip(lst1, lst2):
        if a != b:
            return False
    return True

are_equal_loop = lists_are_equal(list1, list2)  # True
Conclusion
In most typical use cases, leveraging the == operator offers the most straightforward and efficient way to determine if two lists are equal in Python. However, depending on the requirements—such as ignoring order or handling duplicates—alternative methods can be utilized effectively.