If you have two lists that have the same content in a different order (1, 2, 3, vs 3, 2, 1) are they they the same or different? Python considers them to be different.
In some cases order may not matter to you, and you just want to know if the same items exist in both lists. When this happens there are a couple ways you compare them.
- You can use the built-in sorted() function. This lets our “if” statement compare an alphanumeric sorted version of the list without modifying the content of the variable. If you print the variable after using sorted() the items are still in the original order.
- Or you can use the .sort() method. This also puts them list items in alphanumeric order, but it additionally stores these changes in the original variable. If you print the variable out after using .sort() they will be shown in the new order.
Example code that illustrates both options:
#!/usr/bin/env python3
list1 = [ 3 , 4 , 5 , 1 , 2 ]
list2 = [ 5 , 4 , 3 , 2 , 1 ]
print("Comparing original lists")
if list1 == list2:
print("Same")
else:
print("Different")
print("list1:" , list1)
print("list2:" , list2)
print("Sort and compare using sorted()")
if sorted(list1) == sorted(list2):
print("Same")
else:
print("Different")
print("list1:" , list1)
print("list2:" , list2)
print("Sort and modify using .sort()")
if list1.sort() == list2.sort():
print("Same")
else:
print("Different")
print("list1:" , list1)
print("list2:" , list2)
The output:
Comparing original lists
Different
list1: [3, 4, 5, 1, 2]
list2: [5, 4, 3, 2, 1]
Sort and compare using sorted()
Same
list1: [3, 4, 5, 1, 2]
list2: [5, 4, 3, 2, 1]
Sort and modify using .sort()
Same
list1: [1, 2, 3, 4, 5]
list2: [1, 2, 3, 4, 5]