How to find a given element in nested lists?
<p>This is my iterative solution:</p>

<pre><code>def exists(key, arg):
    if not arg:
        return False
    else:
        for element in arg:
            if  isinstance(element,list):
                for i in element:
                    if i==key:
                        return True
            elif element==key:
                return True
    return False
print(exists("f", ["a", ["h", "e", "j"], ["t", "e", "s", "c", "o"]]))
</code></pre>

<p>However, my L.A. wants a double recursive function to solve this.</p>

<p>my attempt:</p>

<pre><code>def exists(key, arg):
    if not arg: //base case
        return False
    elif arg[0]==key: //if we find the key from the first trial
        return True
    else:
        return (exists(arg[0:],key))
</code></pre>

<p>This doesn't work; it shouldn't, because there is no stop. Also, it does not account for lists of lists; I don't know how to do that.</p>

<p>Any answer, comment, etc. is appreciated</p>

<pre><code>def exists(k, l):
    if not isinstance(l, list):
        return False
    if k in l:
        return True
    return any(map(lambda sublist: exists(k, sublist), l))
</code></pre>

python recursion functional-programming