How do I check if an element is in a nested list?
I am trying to define a function nested(x, ys) that tests if a value x appears inside of a nested list of integers ys. The result has to have the value True of False.
Loop over the nested lists and test those; the any() function makes this efficient:
def nested(x, ys):
return any(x in nested for nested in ys)
This assumes ys is nested to one level only.
If recursion is required, you could use:
def flatten(lst):
for elem in lst:
if isinstance(elem, (list, tuple)):
for nested in flatten(elem):
yield nested
else:
yield elem
def nested(x, ys):
return any(x == nested for nested in flatten(ys))
I used a simplified test for list and tuple only to avoid 'flattening' strings.
This will work for any level of depth:
import collections
def nested(x, ys):
if x in ys: return True
# only keep iterables
nests = [y for y in ys if isinstance(y, collections.Iterable)]
# call nested() on each iterable
return any(nested(x, nest) for nest in nests)
# returns True, will go into multiple nests to find 5
print nested(5, [[1,2],[3,4],[1,2,[3,5]]])
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