Wiggs Wiggs - 2 months ago 5
Python Question

How do I break down this list comprehension in Python?

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.

So for example:

>>>findTheLetters(["hello", "world"], "hold")
>>>True
>>>findTheLetters(["hello", "world"], "holn")
>>>False (because of no "n")


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

return all((any(letter in word for word in myList)) for letter in myString)


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.

My attempt:

def findTheLetters(myList, myString):
for word in myList:
for letter in word:
#something goes here?
return letter in myString


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.

BPL BPL
Answer

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

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")

Output:

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
--------------------------------------------------------------------------------

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

Hope it helps

Comments