Why do these bits of code not work the same? (python list comprehension question)

Question:

Shouldn’t these two functions return the exact same thing?

def wordlist(text):
    words = []
    for word in text.split():
        if word.isupper():
            words.append(word)
        else:
            break
    return words
def wordlist(text):
    return [word for word in text.split() if word.isupper()]
Context

I’m doing some python exercises on an educational IDE that ‘tests’ my code by passing various inputs to it. The 1st version of the function is the provided solution which passes all the tests. The 2nd version is mine and it passes most of the tests but fails some hidden test that I can’t see. My understanding is that these two functions should do exactly the same thing. What am I not understanding?

Here are some examples of test inputs that the 2nd function passed:

>>> wordlist("HOW MUCH WOOD cOuLd a k9 chuck") 
>>> ['HOW', 'MUCH', 'WOOD']
>>>
>>> wordlist("9R 4J7L EOS B4d")
>>>['9R', '4J7L', 'EOS']

Sorry that I can’t provide details of the input it’s failing. I can’t actually see it because it’s a "hidden test".

Asked By: pyn00b

||

Answers:

Because of the break statement the first version will only output the first 2 "UPPERS" in "UPPER UPPER lower UPPER", while the 2nd version will output the 3 "UPPER"s

Answered By: Janilson

In version 1, if the condition word.isupper() is not fulfilled, the break statement will be executed, which exits the for loop entirely. This means that the code will immediately return the list words, and any following words will not be added to the returned list. If you want version 1 to have the same output as version 2, try replacing the break statement with a continue statement.

Answered By: Gavin Wong
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.