Search code examples
pythonpython-3.xlistvariablesiterable

Making a list (or iterable) of variables refer to the variables [Python]


Is there a way in Python (preferably 3.6 +) to make a list made from variables to refer the variables themselves, and not their values?

An example:

a, b, c = 1, 2, 3
l = [a, b, c]
print(l)
# Outputs: [1, 2, 3]
# I want: [a, b, c]
# Not preferred but acceptable: ['a', 'b', 'c']

Is this even possible? I'm using python 3.8.

In response to the comments: Any iterable is acceptable. I actually have a similar question on how to delete a variable given it's name as a string, but that's a topic for another question. This does relate to that though, so I decided to check if it was possible.


Solution

  • In Python, variables are internally stored in dictionary. Through these dictionaries, you can access and delete variables by giving their names as strings. Example:

    a, b, c = 1, 2, 3
    names = ['a', 'b', 'c']
    
    for name in names:
        print(globals()[name])
    
    print(a)
    del globals()['a']
    print(a) # a has been removed
    

    Use globals() for global variables, locals() for local variables or object.__dict__ for object members.