Reputation: 123
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?
Upvotes: 12
Views: 20799
Reputation: 395793
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.
Upvotes: 3
Reputation:
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
andnot in
test for membership.x in s
evaluates to true ifx
is a member ofs
, and false otherwise.x not in s
returns the negation ofx in s
.
Upvotes: 2
Reputation: 1124778
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
Upvotes: 17