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,158
  • 3
  • 33
  • 35
NIKHIL RANE
  • 3,814
  • 2
  • 20
  • 42

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
  • 29,394
  • 6
  • 53
  • 86