Incrementing different variables via the ternary operator in a for loop

Viewed 1734

I'm trying to add to a different variable based on a test, within my for loop:

for i in range(alist.__len__()):
        if alist[i] is not blist[i]:
            ascore +=1 if alist[i] > blist[i] else bscore+=1
    print(ascore,bscore)

This code does not work. What I understand is happening is that the if condition is not applying to the whole assignment (we increment ascore if condition), it is instead applying to my value 1 (we increment ascore by 1 if condition). I would prefer functionality similar to the first. Anything I can do here? I understand just breaking it down into if elsif could easily solve this particular problem, but I ma more interested in the way the ternary operator (one line conditionals) work in python. Thankyou!

4 Answers

No. Unfortunately, you cannot use the ternary operator. As the name implies, it's an operator, so both the left hand and right hand sides must be expressions. However, unlike many other languages, Python assignments are statements, thus they cannot be used in the place of an expression.

The solution, as you correctly noted, is to use a normal conditional statement:

for i in range(len(list)):
        if alist[i] is not blist[i]:
            if alist[i] > blist[i]:
                ascore +=1 
            else:
                bscore +=1
    print(ascore, bscore)

If you do not insist on using augmented assignmeng, you can do it like this:

ascore, bscore = (ascore + 1, bscore) if alist[i] > blist[i] else (ascore, bscore + 1)

Thanks to ShadowRanger for pointing my mistake (I missed the parentheses).

If you need to increment only two variables - you could do it via dictionary, with the following code:

scores = {
    True: 0,   # ascore
    False: 0   # bscore
}

for i in range(len(alist)):
    if alist[i] is not blist[i]:
        scores[alist[i] > blist[i]] += 1

print(scores)

Or same, but more clear:

scores = {
    'ascore': 0,
    'bscore': 0
}

for i in range(len(alist)):
    if alist[i] is not blist[i]:
        scores['ascore' if alist[i] > blist[i] else 'bscore'] += 1

print(scores)

you should also make sure you use != and normal if statements

for i in range(len(alist)):
    if alist[i]!=blist[i]:
        if alist[i]>blist[i]:
            ascore+=1
        else:
            bscore+=1
    print(ascore,bscore)
Related