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?
Method 1: Using isinstance() With any() methods that will help us to check the list if it is nested or not. What is this? ◉ isinstance is a built-in method in Python which returns True when the specified object is an instance of the specified type, otherwise it returns False .
The most convenient way to check whether the list contains the element is using the in operator. Without sorting the list in any particular order, it returns TRUE if the element is there, otherwise FALSE. The below example shows how this is done by using 'in' in the if-else statement.
Python provides an option of creating a list within a list. If put simply, it is a nested list but with one or more lists inside as an element. Here, [a,b], [c,d], and [e,f] are separate lists which are passed as elements to make a new list. This is a list of lists.
issubset() function. The most used and recommended method to check for a sublist. This function is tailor made to perform the particular task of checking if one list is a subset of another.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With