2
votes

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.

1
why would you want to do that? - miraculixx
Seriously, think about using a dictionary. - Moritz
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
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 supports Monica

1 Answers

-1
votes

You could use exec.

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

enter image description here