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>The logic is to iterate each element in your list and check: </p>

<ul>
<li><em>if list:</em> call the function again with the sub-list.</li>
<li><em>if equals the key:</em> return True</li>
<li><em>else:</em> return False  </li>
</ul>

<p>Below is sample code to find whether <code>key</code> exists or not in nested list</p>

<pre><code>def exists(key, my_list):
    for item in my_list:
        if isinstance(item, list):
            if exists(key, item):  # &lt;--Recursive Call
                return True
        elif item == key:
            return True
    return False

# Example
&gt;&gt;&gt; my_list = [[[1, 2, 3, 4, 5], [6, 7,]], [8, 9], 10]
&gt;&gt;&gt; exists(2, my_list)
True
&gt;&gt;&gt; exists(6, my_list)
True
&gt;&gt;&gt; exists(8, my_list)
True
&gt;&gt;&gt; exists(10, my_list)
True
&gt;&gt;&gt; exists(11, my_list)
False
</code></pre>

python recursion functional-programming