Fatmir Alijaj
Fatmir Alijaj

Reputation: 53

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

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.

Upvotes: 4

Views: 3062

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1123480

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.

Upvotes: 7

bcorso
bcorso

Reputation: 47138

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]]])

Upvotes: 2

Related Questions