In multiple golfs I've done in Python, a fixed value is assigned to one of two variables chosen by a Boolean. The chosen variable is overwritten by the given value, and the other is unchanged.
if b:y=z else:x=z
Assigning a conditional value is easy, but assigning to a conditional variable seems clunky. I'm wondering if there's a shorter way I'm missing.
This would be easy if
x,y were instead a list
L, but assume the context requires referring to the variables enough that writing
L is prohibitive. Converting takes too long:
The fastest way I know is with a Python 2
exec, which is bizarre:
16 chars, Python 2:
Tuple-choosing seems to be longer:
18, 19, 18, 18 chars:
x,y=b*(x,z)or(z,y) x,y=[z,x,y,z][b::2] y,x=[y,z,x][b:b+2] y,x,*_=[y,z,x][b:] # Python 3
Is there some shorter method or character-saving optimization? You can assume
1, not just Falsey or Truthy, and also make assumptions about the data types and values if it helps.