This is a tips question for golfing in python.
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.
17 chars:
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[0]
and L[1]
is prohibitive. Converting takes too long:
20 chars:
L=[x,y];L[b]=z;x,y=L
The fastest way I know is with a Python 2 exec
, which is bizarre:
16 chars, Python 2:
exec"xy"[b]+"=z"
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 b
is 0
or 1
, not just Falsey or Truthy, and also make assumptions about the data types and values if it helps.
x,y=C(x,y,z,b)
(14 chars) and push any of these implementations into the body ofC
. \$\endgroup\$