How to Compare Lists in Python

To compare lists in Python, you can use the == operator, the != operator, the sorted() function with the == operator, or the set() function along with the <= operator.

The following examples show how to compare lists in Python using different methods.

Using == Operator

We can use the == operator to compare lists.

Suppose we have the following lists:

# Declare lists
list1 = [1, 2, 3]
list2 = [1, 2, 3]

# Compare lists
print(list1 == list2)

Output: 👇️

True

In this example, we use the == operator to compare list1 and list2. The output shows True, which means both lists are equal.

Using != Operator

We can use the != operator to compare lists.

Suppose we have the following lists:

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

# Compare lists
print(list1 != list2)

Output: 👇️

True

In this example, we use the != operator to compare list1 and list2. The output shows True, which means the lists are not equal.

Using sorted() Function & == Operator

We can use the sorted() function and the == operator to compare lists.

Suppose we have the following lists:

# Declare lists
list1 = [1, 2, 3]
list2 = [3, 2, 1]

# Compare lists
print(sorted(list1) == sorted(list2))

Output: 👇️

True

In this example, we use the sorted() function to sort the elements of list1 and list2, and then use the == operator to compare the sorted lists. The output shows True, which means both lists are equal.

Using set() Function & <= Operator

We can use the set() function and the <= operator to compare lists.

Suppose we have the following lists:

# Declare lists
list1 = [1, 2, 3]
list2 = [3, 2, 1]

# Compare lists
print(set(list1) <= set(list2))

Output: 👇️

True

In this example, we use the set() function to convert list1 and list2 to sets, and then use the <= operator to compare the sets. The output shows True, which means both lists are equal.

Conclusion

We can use the == operator, the != operator, the sorted() function with the == operator, and the set() function along with the <= operator to compare lists in Python. These methods provide a convenient way to determine if lists are equal or not.