Sling Academy
Home/Python/Python: How to Compare 2 Lists (3 Approaches)

Python: How to Compare 2 Lists (3 Approaches)

Last updated: June 16, 2023

Comparing 2 lists in Python refers to determining whether the lists are equal or have any differences. Equality between lists is typically defined as having the same elements in the same order. However, in some specific use cases, 2 lists can be considered equal if they have the same elements regardless of the order.

Using the == operator (strict comparison)

This approach simply uses the == operator to compare 2 lists element-wise and returns True if they have the same length and the same elements in the same order and False otherwise. It also works for any type of element, even if they are not hashable or mutable.

Example:

list_a = ['a', 'b', 'c', [1, 2, 3], {'sling': 'academy'}]
list_b = ['a', 'b', 'c', [1, 2, 3], {'sling': 'academy'}]
list_c = ['a', 'b', 'c', [1, 2, 3, 4], {'sling': 'academy'}]

# compare list_a and list_b
if list_a == list_b:
    print('list_a and list_b are equal')
else:
    print('list_a and list_b are not equal')

# compare list_a and list_c
if list_a == list_c:
    print('list_a and list_c are equal')
else:
    print('list_a and list_c are not equal')

Output:

list_a and list_b are equal
list_a and list_c are not equal

Using the sorted() function and the == operator (loose comparison)

In case you want to check for equality regardless of the original order of the elements in the lists, this is the go-to solution. The main idea here is to use the sorted() function to sort both lists and then uses the == operator to compare them element-wise.

Example:

# Define 2 lists
list1 = [1, 2, 3, 4, 5]
list2 = [5, 4, 3, 2, 1]

# Sort both lists and compare them using the equality operator
result = sorted(list1) == sorted(list2)

# Print the result
print(result)

Output:

True

There is an important point you should be aware of. That is a limitation of the sorted() function. It can only sort elements that are comparable, which means they have a defined order and can be compared using the < operator. If you want to sort a list that contains different types of elements, you may need to use a custom key or comparator function that defines how to compare them. For example, you can use the str() function to convert every element into a string and then sort them lexicographically:

# Define 2 lists
list_a = ['a', 'b', 'c', [1, 2, 3], {'sling': 'academy'}]
list_b = [{'sling': 'academy'}, 'c', 'b' ,'a', [1, 2, 3], ]

# Sort both lists and compare them using the equality operator
result = sorted(list_a, key=str) == sorted(list_b, key=str)

# Print the result
print(result)

Output:

True

Using the all() and zip() functions (flexible comparison)

This approach uses the all() function and the zip() function to compare 2 lists element-wise. It returns True if they have the same length and every pair of corresponding elements are equal, and False otherwise.

Example:

list_a = ['a', 'b', 'c', [1, 2, 3], {'sling': 'academy'}]
list_b = ['a', 'b', 'c', [1, 2, 3], {'sling': 'academy'}]

# Use zip() and all() to compare the lists element-wise
result = all(x == y for x, y in zip(list_a, list_b))

# Print the result
print(result)

Output:

True

This approach is more verbose than the first approach, but it provides flexibility to define custom comparison logic. Short circuits if a mismatch is found.

Next Article: Python: Checking If a List Contains an Element (3 Approaches)

Previous Article: Python: How to Swap 2 Elements in a List (2 Approaches)

Series: Python List Tutorials (Basic and Advanced)

Python

You May Also Like

  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types
  • Python: Typing a function with *args and **kwargs