How to check if an element is in a nested list?

python

Solution

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.

Problem

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`.

Original source