How do I break down this list comprehension in Python?
<p>I seen a question earlier on how to find the characters to a specific word from a list of strings. It got deleted I think because I can't find it anymore.</p>

<p>So for example:</p>

<pre><code>&gt;&gt;&gt;findTheLetters(["hello", "world"], "hold")
&gt;&gt;&gt;True
&gt;&gt;&gt;findTheLetters(["hello", "world"], "holn")
&gt;&gt;&gt;False (because of no "n")
</code></pre>

<p>So I seen a post by someone on here saying to use list comprehension like so:</p>

<pre><code>return all((any(letter in word for word in myList)) for letter in myString)
</code></pre>

<p>my question is, is how would I break down that list comprehension so I can understand how it works? I've used simple(newbie) list comprehension but nothing like that.</p>

<p>My attempt:</p>

<pre><code>def findTheLetters(myList, myString):
    for word in myList:
        for letter in word:
            #something goes here?
        return letter in myString
</code></pre>

<p>That is the farthest I've gotten. It works sometimes like with "lord" and "hold", but like if I try "hell" or "woe" for example it still gives me false even though the characters "h" "e" "l" "l" and "w" "o" "e" are in the list of words. I am unsure what I need to add to make it work like the comprehension does.</p>

<p>Here's a little educative example to show you what that algorithm is doing behind the curtains:</p>

<pre><code>def findTheLetters(myList, myString):
    return all((any(letter in word for word in myList)) for letter in myString)


def findTheLetters1(myList, myString):
    res1 = []
    for letter in myString:
        res2 = []
        for word in myList:
            res2.append(letter in word)

        print(letter, res2, any(res2))

        res1.append(any(res2))

    print('-' * 80)
    print(res1, all(res1))
    print('-' * 80)
    return all(res1)

findTheLetters1(["hello", "world"], "hold")
findTheLetters1(["hello", "world"], "holn")
</code></pre>

<p>Output:</p>

<pre><code>h [True, False] True
o [True, True] True
l [True, True] True
d [False, True] True
--------------------------------------------------------------------------------
[True, True, True, True] True
--------------------------------------------------------------------------------
h [True, False] True
o [True, True] True
l [True, True] True
n [False, False] False
--------------------------------------------------------------------------------
[True, True, True, False] False
--------------------------------------------------------------------------------
</code></pre>

<p>I'd recommend you learn &amp; read a about any/all operators and also about nested comprehension lists to know the order of execution.</p>

<p>Hope it helps</p>

python string list python-3.x list-comprehension