Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Check if list of lists of lists contains a specific list

Tags:

python

list

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?

like image 935
Henrique Sousa Avatar asked Mar 18 '14 15:03

Henrique Sousa


People also ask

How do you check if a list is in a list of list Python?

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 .

How do I check if a list contains a list?

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.

Can you have a list of list of lists in Python?

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.

How do you check if a list is subset to another list in Python?

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.


1 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
like image 175
Martijn Pieters Avatar answered Sep 25 '22 20:09

Martijn Pieters