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>If we consider these cases:</p>

<ul>
<li><code>my_list</code> is empty: the key isn't found</li>
<li><code>my_list</code> is not a list: the key isn't found</li>
<li><code>my_list</code> is a non-empty list (two cases):

<ul>
<li><code>my_list[0]</code> is the key: it was found</li>
<li>otherwise, look for the key in both <code>my_list[0]</code> and <code>my_list[1:]</code></li>
</ul></li>
</ul>

<p>the code would be</p>

<pre><code>def exists(key, my_list):
    if not isinstance(my_list, list) or not my_list:
        return False

    return (my_list[0] == key
            or exists(key, my_list[0]) 
            or exists(key, my_list[1:]))
</code></pre>

<p>or even</p>

<pre><code>def exists(key, my_list):
    return (isinstance(my_list, list)
            and len(my_list) &gt; 0 
            and (my_list[0] == key
                 or exists(key, my_list[0])
                 or exists(key, my_list[1:])))
</code></pre>

python recursion functional-programming