0

Is it possible to name the variables in Python by programs:

For instance, something like:

for i in range(3):
  var_%%i = i

And after the piece of code, we will have three variables: var_0, var_1 and var_2.

mommomonthewind
  • 4,390
  • 11
  • 46
  • 74
  • 2
    Do *not* use dynamic variables. It is almost 100% certainly unneeded. Instead, use a *container*, like a list or a dict. – juanpa.arrivillaga Dec 14 '18 at 00:30
  • Yeah, my answer is there to answer your question, but (heh, never thought I would be saying this) please **don't** use it. You're better off using some sort of a container. See the marked duplicate question for more information. – miike3459 Dec 14 '18 at 00:32

1 Answers1

2

Is it possible to name the variables in Python by programs

Yes, but it is really, extremely bad practice.

And after the piece of code, we will have three variables: var_0, var_1 and var_2.

If you really want to do this, you could use exec (note - REALLY bad idea, security issues and all that):

for i in range(3):
  exec("var_" + str(i) + " = i")

However, DO NOT DO THIS. IT IS BAD PROGRAMMING PRACTICE

See this question for a more practical solution involving dictionaries.

Also, see this answer about a second approach, and why it is VERY, very bad to use either of the approaches.


But seriously.

Don't do it.

miike3459
  • 1,431
  • 2
  • 16
  • 32