Reputation: 1603
I have a list in a list.
I want to find whether it contains an item of interest.
For example: L=[['READ',[A,B],'2'],['WRITE',[C,D],'2']]
Now, I have a string, str=READ
, I want to iterate over the two lists, including the sub lists to find whether such an element is present. Is there a way to do it without resorting to using indexes?
I do not want to use indexing because there is no guarantee of the list length remaining same.
Upvotes: 2
Views: 101
Reputation: 114461
Provided there are no loops in the data stucture being searched this is a simple recursive problem:
def find(x, L):
return x in L or any(find(x, sublist)
for sublist in L
if isinstance(sublist, list))
if instead there can be loops in the data structure then you must guard against entering infinite recursion
def find(x, L, seen=None):
if seen is None:
seen = set()
if id(L) in seen:
# Avoid infinite recursion
return False
seen.add(id(L))
return x in L or any(find(x, sublist, seen)
for sublist in L
if isinstance(sublist, list))
Upvotes: 2
Reputation: 59974
Using a common flattening function:
import collections
def flatten(l):
for el in l:
if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
for sub in flatten(el):
yield sub
else:
yield el
You can flatten the list and then check if READ is in it.
>>> 'READ' in flatten(L)
True
Upvotes: 2