4

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.

5
  • 3
    Can we see your effort? Commented Nov 30, 2013 at 0:29
  • 2
    Is ys a known depth (ie a 2d array) or variable depth (ie a tree)? Commented Nov 30, 2013 at 0:29
  • def nested(x,ys): if type(ys[0]) == type([]): return (nested(x,ys[0]) or nested(x,ys[1:])) else: if x == ys[0]: return True else: return False Commented Nov 30, 2013 at 0:53
  • This is my effort until now... Commented Nov 30, 2013 at 0:54
  • for instance, ys = [[2,1,],3] Commented Nov 30, 2013 at 0:55

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I take it there is no recursive nested check in the standard library then?
There is not; arbitrarily-nested lists are not that uniform to fit a standard function, I'd say.
Dank je wel, Martij Pieters!
2

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

3 Comments

Thanks bcorso. But this is too advanced for me. It works, of course. Thanks.
How can I use the function nested as a recursion in order to solve the problem?
This does use recursion. any(nested(x, nest) for nest in nests) recursively calls nested on any iterable element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.