1

I have lists a1, a2, ... , a16 with certain values.

For example:

a1 = [1, 17, 33, 49, 65, 81, 97] 

Then I'm creating a dictionary which makes use of these lists:

dct = {'0110': a1} 

And then I try to create a reference to the variables using the following:

x = 1
x2 = 'a{0}'.format(x)

However when I print(x2) the value being returned is a1 and not [1, 17, 33, 49, 65, 81, 97]

How do I get the actual output of the original a1?

Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
Tomasz Przemski
  • 1,127
  • 9
  • 29

1 Answers1

1

When you create the variable x2 i.e (x2 = 'a{0}.format(x)) - you are creating a new variable x2 as a string which contains the letters of your variable name, not as an actual reference to the variable.

If you want to get the value of your variable based on a string, you need to access the globals() dictionary

>>> a1 = 1
>>> a2 = 2
>>> mylist = [a1, a2]
>>> x = 1
>>> x2 = 'a{0}'.format(x)
>>> print(x2)
a1
>>> print(globals()[x2])
1
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65