4

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

oli5679
  • 1,709
  • 1
  • 22
  • 34
Luthfi
  • 274
  • 4
  • 12
  • 2
    I don't understand the question. If you want to test if numbers in `list_1` are in `list_2`, why would you do validation between `list_2` and `list_3`? And why would that cause it to return `False`? – Barmar Jan 01 '17 at 10:09
  • Convert the lists to `set`, then use `set.issubset()` to tell if one list contains another. – Barmar Jan 01 '17 at 10:10
  • Using sets is slower. See link at the bottom. Also, I think OP doesn't want to compare for trivial subsets but equality, rending your answer possibly incorrect. Oh and possible duplicate of http://stackoverflow.com/q/7828867/5775722 – FMaz Jan 01 '17 at 10:30
  • Thanks for the reply @Barmar, I want to check if numbers inside one list are equal with another, then the values inside them must be same – Luthfi Jan 01 '17 at 10:35
  • Now I understand. What you want is `validate(list_1, list_2)` is true, but `validate(list_2, list_3)` is false. – Barmar Jan 01 '17 at 10:38

1 Answers1

4

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.

oli5679
  • 1,709
  • 1
  • 22
  • 34