-1

For example, if I have S=['a','b','c'], I want to have 3 variables a_value=0, b_value=0, c_value=0. Maybe I am approaching it a wrong way, but at the moment that is what I am trying to do!

  • a_value, b_value, c_value = ['a', 'b', 'c']? – user2263572 Jan 27 '19 at 02:59
  • 7
    Yes, dynamic variable names is always approaching it the wrong way. Maybe looking for a dict, `values = {'a': 0, 'b': 0, 'c': 0}` where you can access `values[x]`. – Ry- Jan 27 '19 at 02:59

2 Answers2

2

Python allows you to dynamically create global (not local) variables by setting them in the dictionary returned by the globals() function. Using your list would look like this:

S = ['a', 'b', 'c']
for v in S:
    globals()[f'{v}_value'] = 0

print(a_value)
print(b_value)
print(c_value)

which prints

0
0
0

as expected. Note that the scope of a "global variable" in Python is the module in which the globals() function is called - this may be different than what you would expect coming from other languages.

As mentioned in comments, there is almost always a better approach that leads to nicer code that is easier to debug.

Chris Hunt
  • 3,840
  • 3
  • 30
  • 46
-2

You can assign the list items with commas

S=['a','b','c']
S[0], S[1], S[2] = 0,0,0
print(S)
>>>
[0, 0, 0]
dsb4k8
  • 61
  • 3