12

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?

0

3 Answers 3

17

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
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.