Creating multiple variables [duplicate]

Never create numbered variable names (1 or 2 maybe, but never 9.) Instead use a list or a dict:

x = dict()
for i in range(1,10,1)
    x[i] = 100 / i
    print x[i] 

(I used a dict in this case because i starts at 1.) However, depending on how you wish to use x further, you may want to use a list instead.


Maybe I should try to convince you that having variables named variable1, variable2, etc. is a bad idea. Since these variables are numbered, they probably have some close relationship to each other. Perhaps they are all numbers. Suppose you wanted to increment all of them by one. You’d have to write repetitious code such as

variable1 += 1
variable2 += 1
variable3 += 1
... etc

instead of

for i in range(1,10,1):
    x[i] += 1

Or perhaps you want to feed all those variables into a function. You’d have to write

func(variable1, variable2, variable3, ...)

instead of

func(**x)

Conclusion: Having numbered variables names is a pain!
Save yourself from pain by using a dict or a list.

Leave a Comment