How to check if a list contains another list with specific elements in Python?

I have a list of lists and you want to check if it already contains a list with certain elements.

From this example, it should be clear:

list = [[1,2],[3,4],[4,5],[6,7]] for test in [[1,1],[1,2],[2,1]]: if test in list: print True else: print False #Expected: # False # True # True #Reality: # False # True # False 

Is there a function that compares list items, no matter how they are sorted?

+4
source share
3 answers

What you want to use is a set: set([1,2]) == set([2,1]) returns True.

So,

 list = [set([1,2]),set([3,4]),set([4,5]),set([6,7])] set([2,1]) in list 

also returns true.

+6
source

If they are actually installed, use the dial type.

 # This returns True set([2,1]) <= set([1,2,3]) 

<= means that "is a subset" when working with sets. See Operations for set types for more details.

+5
source

if you want to get [1,2] = [2,1], you should not use a list. Set the correct type. On the list, the order of the components matters, not on the set. That is why you are not getting "False True True."

+1
source

All Articles