w3resource

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:

Flowchart - Python Collections: Compare two unordered lists.

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.



Follow us on Facebook and Twitter for latest update.