Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 658
Fatmir Alijaj Avatar asked Oct 29 '25 14:10

Fatmir Alijaj


2 Answers

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.

like image 169
Martijn Pieters Avatar answered Nov 01 '25 06:11

Martijn Pieters


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]]])
like image 22
bcorso Avatar answered Nov 01 '25 06:11

bcorso



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!