Makis Renieris
Makis Renieris

Reputation: 17

Variable "generator" on Python using other variables

I am wondering, if it is possible to create variables and name the using strings and other variables on Python. It would really help me on sth I'm making.

For example i want to create 10 variables:

var0
var1
var2
...

I have tried doing it with the "for" loop like this:

for i in range(10):
    'var'+str(i) = 0

but it gives me an error. Please help!

Any help would be much appreciated.

Upvotes: 0

Views: 169

Answers (3)

Blender
Blender

Reputation: 298076

You need to use a list, not a ton of variables:

>>> var = [1, 2, 5, 6, 7, 10]
>>> var[1]
2
>>> var [2]
5
>>>

My rule of thumb is that if more than three variables have similar names (var1, var2 and var3, for example), put them in a list.

Upvotes: 6

Yevgen Yampolskiy
Yevgen Yampolskiy

Reputation: 7180

Here is what you can do:

for i in range(10):
    locals()['var' + str(i)] = 0

print var3

Upvotes: -1

Tim Pietzcker
Tim Pietzcker

Reputation: 336098

You don't want to be using "variable variables". You want to use a dictionary:

>>> vars = {i:0 for i in range(10)}
>>> vars
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}

Now you can access each element like this var[6] (and you're not limited to integers as dictionary keys, either: var["yay!"] = "Great!").

Of course, for the special case of a range of 0 to 9, you can also simply use a list:

>>> vars = [0 for i in range(10)]
>>> vars
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Upvotes: 6

Related Questions