0

i'm fairly new to Python (using 2.7) and have run into an issue with assigning to variables.

I'm trying to assign a number to a variable and then use that variable to create a new variable and assign a list (or a value) to it. For example:

x = 15
"MA"+str(x) = [12,54]
print MA15

The print MA15 should return the list [12,54]. The error I get is 'SyntaxError: can't assign to operator'.

I've tried other methods such as {"%s%s" % ("MA", str(Days))}, {exec()}, and {setattr()} functions.

  • 1
    Would the use of a dictionary be sufficient for your needs? Then you could create the dict with, say `my_dict = dict()`, and then populate it with `my_dict['MA'+str(x)] = [12,54]`. Finally you could get the output with `print my_dict['MA15']`. – Thomas Kühn Jul 07 '17 at 11:31
  • The other choice would be to use the `eval` function, but I do not recommend it. – Thomas Kühn Jul 07 '17 at 11:32
  • 1
    One would have to use `exec` instead of `eval`, see [here](https://stackoverflow.com/questions/5599283/how-can-i-assign-the-value-of-a-variable-using-eval-in-python). This would be done with `exec("MA"+str(x)+" = [12,54]")`. [Here](http://lucumr.pocoo.org/2011/2/1/exec-in-python/) is more on why that is not recommended. – Michael H. Jul 07 '17 at 11:37
  • Your desired result is bad programming style. Just why do you want to do it that way? A dictionary would be much easier and better style. – Rory Daulton Jul 07 '17 at 11:37
  • Hi, thanks for the reply, i see how that works, and it does work in my situation. But is there anyway to have 'MA15' (or any value of x) as a separate variable so that {print MA15} works? -- Edit Using the exec() method detailed makes the {print MA15} work. Thanks again – TABindenter Jul 07 '17 at 11:39
  • Yes, the one using `exec` I suggested. Just replace the second line of your code with `exec("MA"+str(x)+" = [12,54]")`. – Michael H. Jul 07 '17 at 11:43
  • @Michael I did not know about `exec` -- thanks for the info! – Thomas Kühn Jul 07 '17 at 11:45

1 Answers1

1

try using exec:

x=15
string="MA%d=[12,54]"%(x)
exec(string)
sam-pyt
  • 1,027
  • 15
  • 26