-2

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.

Codeman
  • 477
  • 3
  • 13

2 Answers2

2

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.

r0the
  • 617
  • 4
  • 13
1

Still not sure what your use case is, but a dictionary might be a good fit:

d = {'a': 1, 'b': 2, 'c': 3}

l = ['a', 'b', 'c']
# or 
# l = list(d.keys())
mozway
  • 194,879
  • 13
  • 39
  • 75
  • This could work, but I do need to do things with `a`, like passing it to functions. Guess I'll do `d['a']` then, if there's no other way. Thanks! – Codeman Feb 26 '22 at 13:42
  • This seems the most reasonable and pythonic – mozway Feb 26 '22 at 13:46