Check if list of lists of lists contains a specific list

Question:

I have a list that contains other lists with coordinates for multiple tile positions and I need to check if that list contains another list of coordinates, like in this example:

totalList = [ [[0,1], [2,7], [6,3]], [[2,3], [6,1], [4,1]] ]

redList = [ [0,1], [2,7], [6,3] ]

if totalList contains redList:
   #do stuff

Can you please help me find out how to do this?

Asked By: Henrique Sousa

||

Answers:

Just use a containment test:

if redList in totalList:

This returns True for your sample data:

>>> totalList = [ [[0,1], [2,7], [6,3]], [[2,3], [6,1], [4,1]] ]
>>> redList = [ [0,1], [2,7], [6,3] ]
>>> redList in totalList
True
Answered By: Martijn Pieters

Just use the in operator:

>>> totalList = [ [[0,1], [2,7], [6,3]], [[2,3], [6,1], [4,1]] ]
>>> redList = [ [0,1], [2,7], [6,3] ]
>>> redList in totalList
True
>>> if redList in totalList:
...     print('list found')
...
list found
>>>

From the docs:

The operators in and not in test for membership. x in s evaluates to
true if x is a member of s, and false otherwise. x not in s returns
the negation of x in s.

Answered By: user2555451

Use the in keyword to determine if a list (or any other Python container) contains an element:

totalList = [ [[0,1], [2,7], [6,3]], [[2,3], [6,1], [4,1]] ]
redList = [ [0,1], [2,7], [6,3] ]
redList in totalList

returns

True

So if you do:

if redList in totalList:
    #do stuff

Your code will then do stuff.


I need to know if totalList contains a list that has exactly the same elements as redList.

We see that list implements __contains__

>>> help(list.__contains__)
Help on wrapper_descriptor:

__contains__(...)
    x.__contains__(y) <==> y in x

and from the docs:

__contains__
Called to implement membership test operators. Should return true if item is in self, false otherwise.

And:

The operators in and not in test for collection membership. x in s evaluates to true if x is a member of the collection s, and false otherwise. x not in s returns the negation of x in s. The collection membership test has traditionally been bound to sequences; an object is a member of a collection if the collection is a sequence and contains an element equal to that object. However, it make sense for many other object types to support membership tests without being a sequence. In particular, dictionaries (for keys) and sets support membership testing.

For the list and tuple types, x in y is true if and only if there
exists an index i such that x == y[i] is true.

So we know that one of the elements must be equal to that of redList.

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.