You can use locals()
, vars()
, or globals()
and inject your variable name there. For eg.
>>> list10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'list10' is not defined
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'x': [], '__name__': '__main__', '__doc__': None}
>>> locals()['list10'] = []
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, 'list10': [], '__package__': None, 'x': [], '__name__': '__main__', '__doc__': None}
>>> list10
[]
Generally, if you're doing something like this, you'd probably be better off with using a dictionary to store the variable name and the value(s).
For eg.
>>> my_lists = {}
>>> my_lists['list10'] = []
And then when you want to look it up, you can .get()
it if you want robustness against a variable name not existing, or directly accessing it if you're going to guard against non-existence yourself.
>>> the_list_i_want = my_lists.get('list10')
>>> the_list_i_want = my_lists['list10'] # Will raise a KeyError if it does not exist