Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if contents of two lists is same in python?

I have 3 lists :

  1. list_1 = [1,2]
  2. list_2 = [2,1]
  3. list_3 = [1,2,3]

Note: numbers inside [] are the ids from Django Model

I want to test whether the contents (but not necessarily the order) of two lists are exactly the same. With reference to the 3 examples above:

Comparing list_1 and list_2
should return True,

but if I do validation between list_2 and list_3, or between list_1 and list_3,
then the result should be False.

How do I achieve this?

Thanks :D

like image 552
Luthfi Avatar asked Oct 14 '25 15:10

Luthfi


1 Answers

I interpret your question as return true if the contents (but not necessarily order) of the lists are identical, otherwise return false. This can be solved by sorting both lists, then using the == for comparison. sorted() returns a list of integers in ascending order. This means that if the lists' contents are the same, sorted() returns identical lists.

def validation(list_1,list_2):
    return sorted(list_1) == sorted(list_2)

This passes all of your test cases. I might have misunderstood your question, please clarify if that's the case.

like image 111
oli5679 Avatar answered Oct 17 '25 04:10

oli5679



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!