nice python solution

Chris Liechti cliechti at
Sun Nov 18 23:20:55 CET 2001

[posted and mailed]

Uwe Schmitt <uwe at> wrote in news:9t95gu$ab7l1$1 at hades.rz.uni-
> Hi,
> i there a nice python shortcut for:
>     if idx=0:
>        a=val
>     elif idx=1:
>        b=val
> ???
> I tried
>    (a,b)[idx] = val
> but this does not work, i get an error message.
> Greetings, Uwe.

if you have an object:
  setattr(obj,('a','b')[idx], val)

or a bit uglier
  obj.__dict__[('a','b')[idx]] = val

some hacky tries:
if a and b are initalized: a,b = idx and (a,val) or (val,b)
if repr gives a valid python expr.: exec '%s=%s'%('a','b')[idx], repr(val))

the cleanest i can find for globals is:
  import __main__
  __main__.__dict__[('a','b')[idx]] = val

depends on your situation, but maybe its easier to use a dict to store the 
d = {}
d[('a','b')[idx]] = val

tell us more about the situation were you use it, maybe there is a complete 
other way to achieve the desired results.

Chris <cliechti at>

More information about the Python-list mailing list