D_C
D_C

Reputation: 390

Variable name from list as string

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'

Upvotes: 1

Views: 2049

Answers (2)

Danny Varod
Danny Varod

Reputation: 18068

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

Upvotes: 1

D_C
D_C

Reputation: 390

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

Upvotes: 0

Related Questions