Python: Compare two unordered lists
Python Collections: Exercise-36 with Solution
Write a Python program to compare two unordered lists (not sets).
Sample Solution:
Python Code:
# Import the Counter class from the collections module
from collections import Counter
# Define a function 'compare_lists' that takes two lists 'x' and 'y' as arguments
def compare_lists(x, y):
# Compare whether the counts of elements in 'x' and 'y' are equal using Counter
return Counter(x) == Counter(y)
# Create two lists 'n1' and 'n2' containing integer values
n1 = [20, 10, 30, 10, 20, 30]
n2 = [30, 20, 10, 30, 20, 50]
# Call the 'compare_lists' function with 'n1' and 'n2' as arguments and print the result
print(compare_lists(n1, n2))
Sample Output:
False
Flowchart:
Python Code Editor:
Previous: Write a Python program to group a sequence of key-value pairs into a dictionary of lists.
Next: Python Data Types: Sets - Exercises, Practice, Solution.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/collections/python-collections-exercise-36.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics