1

I have been looking for a way to get a variable name in an array as string. eg.:

a = ['1x', '2y', '3z']
b = ['1xx', '2yy', '3zz']
c = ['1xxx', '2yyy', '3zzz']
arr = [a, b, c]
    
for x in arr:
    print('Currently executing: ', x)
    for e in x:
        print('Return Value: ', e)
    
>>Currently executing: a
>>Return Value: 1x
>>Return Value: 2y
>>Return Value: 3z
>>Currently executing: b
>>Return Value: 1xx
>>Return Value: 2yy
>>Return Value: 3zz
>>Currently executing: c
>>Return Value: 1xxx
>>Return Value: 2yyy
>>Return Value: 3zzz

So far, I have been unsuccessful in my search. There are answers posted on this problem with variables outside of arrays, but I have yet been able to transform them to my context. (eg: How to print original variable's name in Python after it was returned from a function?)

Update

I've tried the vars()[name] in a few different ways, but none are working. I don't think I understand the implementation in my context. Can you elaborate?

print(vars()[arr])
print(vars()[x])
print(vars()[e])

All return :

Traceback (most recent call last): File "C:/Users/wxy/Desktop/thread_test.py", line 9, in print('Return Value: ', vars()[arr]) TypeError: unhashable type: 'list'

D_C
  • 370
  • 4
  • 22
  • 5
    You need to keep track of this string yourself. Barring various hacks and tricks, the way to do this correctly is to group the data that you want together using the appropriate data structure. variables are for programmers reading and writing *source code*, they shouldn't be considered program data. There are various approaches here, you could use a `dict` that maps strings to lists, or a list of tuples, `arr = [('a', a), ('b', b), ('c', c)]`. Or create a custom class, with a `name` attribute and `.arr` attribute and put that in a list. – juanpa.arrivillaga Jan 31 '21 at 19:58
  • 1
    As an aside, these are not arrays, they are *lists* – juanpa.arrivillaga Jan 31 '21 at 19:59
  • Very good example to "making things more complicated than they need to be". Just use a dictionary. Get the keys and the values from wherever you want them from and update the dict accordingly. – Ezio Feb 01 '21 at 05:16

2 Answers2

1

vars()[name] or globals()[name] depending on scope on variable but do not do this! Instead return a Dict or a Tuple.

Danny Varod
  • 17,324
  • 5
  • 69
  • 111
0

I just re-tried a solution already posted answer for my context

a = ['1x', '2y', '3z']
b = ['1xx', '2yy', '3zz']
c = ['1xxx', '2yyy', '3zzz']
arr = [a, b, c]

for name in arr:
    xx = [tpl[0] for tpl in filter(lambda x: name is x[1], globals().items())][0]
    print(xx)

>>a
>>b
>>c
D_C
  • 370
  • 4
  • 22