How to Create Variable Variables

How do I create variable variables?

You can use dictionaries to accomplish this. Dictionaries are stores of keys and values.

>>> dct = {'x': 1, 'y': 2, 'z': 3}
>>> dct
{'y': 2, 'x': 1, 'z': 3}
>>> dct["y"]
2

You can use variable key names to achieve the effect of variable variables without the security risk.

>>> x = "spam"
>>> z = {x: "eggs"}
>>> z["spam"]
'eggs'

For cases where you're thinking of doing something like

var1 = 'foo'
var2 = 'bar'
var3 = 'baz'
...

a list may be more appropriate than a dict. A list represents an ordered sequence of objects, with integer indices:

lst = ['foo', 'bar', 'baz']
print(lst[1]) # prints bar, because indices start at 0
lst.append('potatoes') # lst is now ['foo', 'bar', 'baz', 'potatoes']

For ordered sequences, lists are more convenient than dicts with integer keys, because lists support iteration in index order, slicing, append, and other operations that would require awkward key management with a dict.

How can you dynamically create variables?

Unless there is an overwhelming need to create a mess of variable names, I would just use a dictionary, where you can dynamically create the key names and associate a value to each.

a = {}
k = 0
while k < 10:
# dynamically create key
key = ...
# calculate value
value = ...
a[key] = value
k += 1

There are also some interesting data structures in the collections module that might be applicable.

How create variable name with other variable's value in it?

This is actually a bad practice to do this. You better to use a dict.

BTW, you can do this:

In [3]: a = "Jack"

In [4]: exec(f'c_{a} = 10')

In [5]: c_Jack
Out[5]: 10


How do you create different variable names while in a loop?

Sure you can; it's called a dictionary:

d = {}
for x in range(1, 10):
d["string{0}".format(x)] = "Hello"
>>> d["string5"]
'Hello'
>>> d
{'string1': 'Hello',
'string2': 'Hello',
'string3': 'Hello',
'string4': 'Hello',
'string5': 'Hello',
'string6': 'Hello',
'string7': 'Hello',
'string8': 'Hello',
'string9': 'Hello'}

I said this somewhat tongue in check, but really the best way to associate one value with another value is a dictionary. That is what it was designed for!

How to create a varying variable name in python

To solve this, you can try something like this:

for x in range(0, 9):
globals()['var%s' % x] = x

print var5

The globals() function produces a list-like series of values, which can be indexed using the typical l[i] syntax.

"var%s" % x uses the %s syntax to create a template that allows you to populate the var string with various values.

How to create automatic variables for large number of values in list. For ex. list with 50 values how can we assign values to 50 different variables

You can use exec which evaluates a string at runtime and then executes it as you were typing it. Combine it with the format specifier and the string concatenations and you have>

s = ""
for i in range(0,10):
s+="x{0} = mylist[{0}]\n".format(i)

mylist = [i*i for i in range(10)]
exec(s)

which is equivalent to typing manually:

x0 = mylist[0]
x1 = mylist[1]
x2 = mylist[2]
x3 = mylist[3]
x4 = mylist[4]
x5 = mylist[5]
x6 = mylist[6]
x7 = mylist[7]
x8 = mylist[8]
x9 = mylist[9]

You can then test it this way:

p = ""
for i in range(10):
p+="print(\"x{0} = \",x{0})\n".format(i)
exec(p)

Which gives you:

x0 =  0
x1 = 1
x2 = 4
x3 = 9
x4 = 16
x5 = 25
x6 = 36
x7 = 49
x8 = 64
x9 = 81

However, quoting this answer

the first step should be to ask yourself if you really need to. Executing code should generally be the position of last resort: It's slow, ugly and dangerous if it can contain user-entered code. You should always look at alternatives first, such as higher order functions, to see if these can better meet your needs.



Related Topics



Leave a reply



Submit