3

here is my python code:

>>> listName = 'abc'
>>> exec(listName+"=[]")
>>> print listName
>>> 'abc'

excepted output:

>>> print listName
>>> []

I want to define a new variable based on that string.

Aleksandr Kovalev
  • 3,508
  • 4
  • 34
  • 36
NIKHIL RANE
  • 4,012
  • 2
  • 22
  • 45

1 Answers1

2

Even though that may be possible for global (and not local) variables, the better, cleaner, simpler, safer, saner (all in one word: pythonic) way is to use a dictionary for dynamic names:

values = {}
varname = get_dynamic_name()
# set
values[varname] = value
# get
values[varname]
bereal
  • 32,519
  • 6
  • 58
  • 104