0

How do I create a loop in which I will create variables with name having the 'i' value at the end of variable's name? So far I have this but it is not working:

for i in range(0,4):
#v{i} should be v1, v2, v3, v4 at the end of loop with values being the 'i' value respectively
v{i} = i
i+=1

Thank you

rogaloo
  • 88
  • 1
  • 10

2 Answers2

1
for i in range(0,4):
    vars()['v' + str(i)] = i
    i+=1
armstar
  • 39
  • 3
0

The answer is that you don't want to do this in such way. If you would want to retrieve a value given a certain "variable" name, I would create a proper Python data structure for it, such as a dictionary:

d = {}
for i in range(0,4):
    d[f"name{i}"] = i
    i+=1

Look at this thread for further explanation and insights why you want to follow this strategy:

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

There you will also find an actual answer on how to technically do what you want in Python, but is discouraged.

mabergerx
  • 1,216
  • 7
  • 19