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.

7
  • 2
    Possible duplicate of How can I assign the value of a variable using eval in python? Commented May 2, 2017 at 19:48
  • 1
    why would you want to do that? Commented May 2, 2017 at 19:48
  • 1
    Seriously, think about using a dictionary. Commented May 2, 2017 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. Commented May 2, 2017 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. Commented May 2, 2017 at 20:02

1 Answer 1

-1

You could use exec.

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

enter image description here

Sign up to request clarification or add additional context in comments.

5 Comments

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.
@user2357112: tested it with python 3.6, see screenshot in answer.
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: 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.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.