Python - Finding lists within a list
-
To check for an item in a list, common suggestion you can find is to use any. This may not be the right solution for us in most cases.
In the sample below, searching for Merc also returns True which may be an issue sometimes as this is not an exact match.
lst = ("Mercury", "Venus", "Earth", "Mars") if (any('Mercury' in i for i in lst)) : print("Planet present") #This could be wrong if we want an exact match if (any('Merc' in i for i in lst)) : print("Planet present")
-
For two-dimensional lists, we will face some additional challenges if we are using any. In below sample which is a list of holidays (a combination of month and day), we will not be able to find an exact match using any.
holidays = ( (1, 20), (1, 25), (1, 15), (3, 1) ) if (any(25 in i for i in holidays)) : print("Present")
-
Best way to check for a list inside another list is to use a function and to do the required checks as in sample below.
Copiedholidays = ( (1, 20), (1, 25), (2, 15), (3, 1) ) def checkForHoliday(item): for m, d in holidays: if(m == item[0] and d == item[1]): return True return False print(checkForHoliday( (1, 20) ))