Check If Two Unordered lists Are Equal in Python.

In this post, we will learn to Check if two unordered lists are equal. which we can perform using making both lists a set that only contains the unique values so it would be more easily for us to compare two strings.



In python, a list is a mutable data structure that could store the data of any data type that we want to store. And when it comes to comparing two lists that are unordered we prefer first to convert the list into the set and then compare them with simply ‘==’.

Converting the list into a set makes all the elements of the list unique and there will not be any duplicate values so it will be easy to compare the list.

list1 = [1, 2, 3, 4, 5]
list2 = [5, 4, 3, 2, 1]

if set( list1) == set( list2):
    print(" The lists are equal")
    print(" The lists are not equal")

Here the above code will result in “The lists are equal” as both the lists have the same elements, Although both lists have different order of elements they are the same.

To learn more about the list visit Understanding Python Dictionary Slicing – Detailed Tutorial with Examples and Problemswher we can easily get to know more about python lists and different operations that could be performed over them and altered as per our choice.

We can also perform the comparison using nested for loop where each element of list1 is compared with the elements of list2 and if all the elements of list1 i=are found in list2 and the size of both the lists are the same in that case the putout will be “The lists are equal”.

And if any of the two conditions is found to be false the output will be different.

To learn more about the comparison of two unordered lists visit: List comparison.

To learn more about different programming languages and the solutions to different problems as detailed tutorials visit: beta python programming languages Solutions.



Leave a Comment

%d bloggers like this: