Skip to content
Advertisement

One liner for True or False for loop in Python

Almost every time I solve an exercise of Codewars and glance at others solutions I see that some guys do my 15 lines code in 2 or 3 lines. So, I have started to learn lists and sets comprehensions and would try other tricks. For now my question is about this code:

    for i in range (0, 3):
        if not text [i].isdecimal ():
            return False 

Is it possible to write it in one line?

Advertisement

Answer

Use all:

return all(text[i].isdecimal() for i in range(0,3))

all iterates through your list/generator/tuple/etc. and evaluates whether each item is true or false. It bails and returns False the first time it evaluates a False. any is similar, except it will look through everything for at least one truthy evaluation.

(I am assuming your original code is correct, and you’re only interested in the first three elements of text, and that you’re looking to return that value from whatever function you’re in.)

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement