user14793744
user14793744

Reputation:

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?

Upvotes: 0

Views: 989

Answers (2)

Nathaniel Ford
Nathaniel Ford

Reputation: 21220

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

Upvotes: 2

PreyZer
PreyZer

Reputation: 51

You have a more complex loop like this:

 for i in range(10):
    if i<5:
        j = i**2
    else:
        j = 0    
    print(j) ```

You can compress this into one line. Check out the following code snippet:

for i in range(10): print(i**2 if i<5 else 0)

Upvotes: 0

Related Questions