Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test if a list contains another list with particular items in Python?

I have a list of lists and want to check if it already contains a list with particular items.

Everything should be clear from this example:

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 the items of the list regardless how they are sorted?

like image 985
Tomas Novotny Avatar asked Dec 16 '22 20:12

Tomas Novotny


2 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.

like image 107
user Avatar answered Jan 04 '23 23:01

user


If they're really sets, use the set type

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

<= means 'is a subset of' when dealing with sets. For more see the operations on set types.

like image 33
Kenan Banks Avatar answered Jan 05 '23 00:01

Kenan Banks