-2

I have 5 variables a,b,c,d and e and I am making a list of those variables. Now I want to loop over the name of them.

a=[1,3,4]
b=[4,5,6]
...
data=[a,b,c,d,e]
for x in ----:
   print(x)

and the output should be like

a
b
c
d
e

thanks!

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
Anne
  • 145
  • 1
  • 4
  • While this could be done with `locals`, a form of reflection, it's probably an X-Y issue. Would using a `dict` (mapping "names" to "values") solve the problem? - https://www.geeksforgeeks.org/python-dictionary/ – user2864740 May 21 '21 at 17:02
  • "a" is a reference to some object and there could be many references to that same object. Python doesn't keep a backlink from an object to whatever variables happen to be referencing it at any given time. You can't get the name of the variable from its value. – tdelaney May 21 '21 at 17:05

1 Answers1

1

You can't do so without changing the data structure of data; the list does not store the "name" of the variables it carries.

(The last sentence might sound a little handwavy to some people; actually you are dealing with objects, which can be accessed by certain names a, ..., e. When you make [a, b, c, d, e], you are creating a list that has a direct access to those objects. The names are not relevant to this list; it just gets to the objects directly.)

One thing you can do is to make a dictionary:

data = {'a': a, 'b': b, 'c': c, 'd': d, 'e': e}

for k in data:
    print(k)

In this way you store the name tag of each item, as well as the its value.

j1-lee
  • 13,764
  • 3
  • 14
  • 26