How to check if an item exist in a nested list

zacherates zacherates at gmail.com
Thu Jul 19 20:31:31 EDT 2007


> One way is to check the length of each dimension. Does any body
> know a simpler way?

No need to check the length of the list:
"""
>>> foo = [0, 1, 2, [3, 4, 5, 6, 7, [8, 9, 10]]]
>>> isInNested(0, foo)
True
>>> isInNested(11, foo)
False
>>> isInNested(3, foo)
True
>>> isInNested(8, foo)
True
"""

def isInNested(k, l):
    try:
        if k in l:
            return True

        for i in l:
            if isInNested(k, i):
                return True
    except TypeError:
        #l is not iterable
        pass

    return False

if __name__ == "__main__":
   import doctest
   doctest.testmod()




More information about the Python-list mailing list