0

in javascript you can do:

i = -1;
array.forEach(function() {
 i++
 eval("var item" + i + " = " + array[0]);
});

to dynamically create variables, used this a couple of times to write data from an external JSON array into divs for each, is something like this possible in python(3.7)? especially the eval() method.

thanks in advance!

Terebo
  • 5
  • 1
  • 2
  • Yes, there is an eval function. But you shouldn't use it. You shouldn't use it in Javascript for this either. – juanpa.arrivillaga May 22 '20 at 07:09
  • 2
    Does this answer your question? [Use of eval in Python?](https://stackoverflow.com/questions/1087255/use-of-eval-in-python) – sushanth May 22 '20 at 07:10
  • You shouldn't do this, here is why: http://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html – buran May 22 '20 at 07:10

1 Answers1

0

Yes there is! You can use the exec function in this case:

i = -1

for value in array:
    i += 1
    exec("item" + str(i) + " = " + str(array[0]))

There are negatives to this though, as stated in the comments already, but assuming you still decide to use it here it is.

qBen_Plays
  • 262
  • 2
  • 9