To compare two unordered lists element by element in Python, you can use the collections.Counter
class or convert the lists to sets. Here are examples using both approaches:
- Using
collections.Counter
:
from collections import Counter
list1 = [1, 2, 3, 4, 5]
list2 = [5, 4, 3, 2, 1]
counter1 = Counter(list1)
counter2 = Counter(list2)
if counter1 == counter2:
print("Lists are equal.")
else:
print("Lists are not equal.")
In this example, we create Counter
objects for both lists using the Counter()
function from the collections
module. The Counter
object counts the occurrences of each element in the list. We then compare the two Counter
objects using the equality (==
) operator. If they are equal, the lists have the same elements regardless of their order, and the condition counter1 == counter2
evaluates to True
. Otherwise, the condition evaluates to False
, indicating that the lists are not equal.
- Using sets:
list1 = [1, 2, 3, 4, 5]
list2 = [5, 4, 3, 2, 1]
set1 = set(list1)
set2 = set(list2)
if set1 == set2:
print("Lists are equal.")
else:
print("Lists are not equal.")
In this example, we convert both lists to sets using the set()
function. Sets are unordered collections of unique elements. We then compare the two sets using the equality (==
) operator. If they are equal, the sets have the same elements, and the condition set1 == set2
evaluates to True
. Otherwise, the condition evaluates to False
, indicating that the lists are not equal.
Choose the approach that suits your specific use case. The Counter
approach can handle repeated elements in the lists, while the set approach considers only unique elements.
+ There are no comments
Add yours