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>

<p>Thanks everyone for your help, here is the answer that I have figured out. While it does not look as elegant as most of the answers that were already provided, this answer is the only answer that my lab instructor will accept as it is a pure functional programming method meaning no side effects or for loops:</p>

<pre><code>def exists(key, seq):
    if not seq:
        return False
    elif seq[0]==key:
        return True
    if isinstance(seq[0],list):
        return(exists(key,seq[0]) or exists(key,seq[1:]))

    else:
        return exists(key,seq[1:])
    return False
print(findkey("s", ["g","t", "e", ["s"], ["l","k","s",["d","f"],"w"], "o"]))
</code></pre>

python recursion functional-programming