-1

I'm wondring if there is any way to create new variables from the name of the currently inspected item in a for loop:

list = ["a", "b", "c"]
for item in list:
    item_new = 1

print a_new 
print b_new
print c_new

What i want this to outputis:

1
1
1

Edit: Ouch, ok, point taken :P

Knew a dict would work in this instance, just wanted to check if the method above was viable. Apparently not!

Jack Pettersson
  • 1,606
  • 4
  • 17
  • 28

3 Answers3

4

You should not do this with variables. A dictionary is what you are looking for:

list = ["a", "b", "c"]
variables = {}
for item in list:
    variables[item] = 1

print variables["a"]
print variables["b"]
print variables["c"]
k-nut
  • 3,447
  • 2
  • 18
  • 28
2

The locals() function returns a reference to a dict where you can inspect local variables, and each key represents the local variable name as an string:

>>> locals()
{'a': 2, 'b': 9, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}
>>> var = "Some text"
>>> locals()
{'var': 'Some text', 'a': 2, 'b': 9, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}

There is also the globals() function that you can also use not only to inspect global variables but also to create new global variables dynamically:

>>> globals()['ZZ'] = 123
>>> ZZ
123

But please, don't do this. This program is unmainteinable. Use a normal dict to create custom elements with your code. This program is way far more readable and maintainable:

list = ["a", "b", "c"]
d = {}
for item in list:
    d[item] = 1

print d['a'] 
print d['b']
print d['c']
martineau
  • 119,623
  • 25
  • 170
  • 301
vz0
  • 32,345
  • 7
  • 44
  • 77
  • The documention for [`locals()`](https://docs.python.org/2/library/functions.html?highlight=locals#locals) specifically says "The contents of this dictionary should not be modified". – martineau Nov 19 '14 at 09:22
1

Instead of creating new variables, a dictionary seems like a better approach.

Also, it's best to not use the variable name list, because that is already the name of a function.

L = ["a", "b", "c"]
d = {}
for item in L:
    d["{}_new".format(item)] = 1

print d["a_new"]
print d["b_new"]
print d["c_new"]
twasbrillig
  • 17,084
  • 9
  • 43
  • 67