2

I want to produce about 100 variables, each assigned to its own integer So for example, number_1=1,number_2=2,number_3=3 etc.. I have tried to use eval in the following way:

for x in range(1,101):
   eval('number_'+str(x)) = x

I receive the error 'cant assign to function call'. I've also tried:

for x in range(1,101):
   eval(('number_'+str(x)) = x)

Which gives the error 'keyword can't be an expression' Is there a way to do this? I am aware of the risks associated with eval and exec, but there is no user input or internet access in my code. Thanks!

Edit: This isn't the same as the other thread suggested, since here I'm trying to alter the name of the variable as well as its value.

JoeP
  • 33
  • 5
  • 2
    Possible duplicate of [How can I assign the value of a variable using eval in python?](http://stackoverflow.com/questions/5599283/how-can-i-assign-the-value-of-a-variable-using-eval-in-python) – bunji May 02 '17 at 19:48
  • 1
    why would you want to do _that_? – miraculixx May 02 '17 at 19:48
  • 1
    Seriously, think about using a dictionary. – Moritz May 02 '17 at 19:49
  • I'm trying to create a moving average of readings from a raspberry pi. I'm sure there are more efficient ways of doing it, but I've wanted to create variables in this way before so I thought I'd ask anyway. – JoeP May 02 '17 at 19:57
  • 4
    Use a list. You only think you want to create variables dynamically because you haven't gotten used to using actual data structures yet. – user2357112 May 02 '17 at 20:02
  • With 100 differently named variables, calculating a moving average would be another nightmare. – DYZ May 03 '17 at 04:27
  • The idea is that I add up all the variables using a similar process: – JoeP May 03 '17 at 04:54

1 Answers1

-1

You could use exec.

for i in range(100):
    exec('number_{0} = {0}'.format(i))

enter image description here

Maximilian Peters
  • 30,348
  • 12
  • 86
  • 99
  • The special-case handling they used in the code generator to make this work in Python 2 went away in Python 3, so [this fails on Python 3](http://ideone.com/lRgOiG). – user2357112 May 02 '17 at 20:04
  • @user2357112: tested it with python 3.6, see screenshot in answer. – Maximilian Peters May 02 '17 at 20:06
  • You tested it outside of a function. It only works outside of a function, and "avoid writing functions" is not a lesson we should be teaching people. – user2357112 May 02 '17 at 20:08
  • @user2357112: I agree with you that it is not a good idea to declare variables outside a function but the question was not 'what is the best way?' but how to do it with `eval` and `exec`. – Maximilian Peters May 02 '17 at 20:13
  • I've just tested it in my code - apparently it doesn't work in python 3 but does in 2. I don't really mind using 2, since my RPi loads it in python 2 automatically. I'd still rather a python 3 solution though – JoeP May 02 '17 at 20:48