In this tutorial, we will learn how to compare two lists in Python. Comparisons between lists are useful in various programming situations, like checking if two lists have the same elements or identifying the differences between them.
Method 1: Using “== ” Operator
One simple way to compare two lists is to use the “== ” operator. This operator checks whether the two lists have the same elements in the exact same order. If they do, it will return True, otherwise, it will return False.
1 2 3 4 5 6 7 8 9 |
list1 = [1, 2, 3, 4, 5] list2 = [1, 2, 3, 4, 5] list3 = [5, 4, 3, 2, 1] comparison1 = list1 == list2 comparison2 = list1 == list3 print(comparison1) print(comparison2) |
Output:
True False
Method 2: Using set() and “==” Operator
If you want to compare whether two lists have the same elements without considering the order, you can convert the lists to sets and then use the “== ” operator.
1 2 3 4 5 6 |
list1 = [1, 2, 3, 4, 5] list3 = [5, 4, 3, 2, 1] comparison_unordered = set(list1) == set(list3) print(comparison_unordered) |
Output:
True
Method 3: Using Counter from the collections module
Using the collections.Counter class, you can compare the frequency of elements in two lists without considering their order.
1 2 3 4 5 6 7 8 |
from collections import Counter list1 = [1, 2, 3, 4, 5] list4 = [5, 4, 3, 2, 1, 1] comparison_frequency = Counter(list1) == Counter(list4) print(comparison_frequency) |
Output:
False
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
list1 = [1, 2, 3, 4, 5] list2 = [1, 2, 3, 4, 5] list3 = [5, 4, 3, 2, 1] list4 = [5, 4, 3, 2, 1, 1] # Method 1: Using "== " Operator comparison1 = list1 == list2 comparison2 = list1 == list3 print(comparison1) print(comparison2) # Method 2: Using set() and "==" Operator comparison_unordered = set(list1) == set(list3) print(comparison_unordered) # Method 3: Using Counter from collections module from collections import Counter comparison_frequency = Counter(list1) == Counter(list4) print(comparison_frequency) |
Conclusion
In this tutorial, we covered three methods to compare two lists in Python. You can use the “== ” operator to compare lists element-wise with the same order, use the set() and the “== ” operator to compare lists without considering the order, or use the collections.Counter class to compare the frequency of elements in two lists without considering their order.
Choose the method that best suits your programming needs.