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