-1

I am trying to create variable for each iteration of the for loop:

for i in range(10):
x(i) = 'abc'

so that I would get x1, x2, x3, x4, .... x10, all equal to 'abc'

Anyone know how to do it? Thanks!

Quy Vu Xuan
  • 159
  • 1
  • 5
  • 13

2 Answers2

4

You should not be doing that, store your values in a dict if you want to access them by name, or a list if you want to access them by index, but if you really insist:

for i in range(10):
    locals()["x" + str(i)] = "abc"  # use globals() to store the vars in the global stack

print(x3)  # abc
zwer
  • 24,943
  • 3
  • 48
  • 66
  • One unlikely situation where such automated variable creation is needed is a call from python to TabPy (Tableau Python Server) via the `query()` function from `tabpy` package. The use of variable-length collection of parameters here is due to Tableau constraints (no multi-column data formats) – mirekphd Mar 15 '20 at 15:54
  • Hello, I agree with you about using a dict instead of creating variables inside the for loop, however if I need to store diferent values per iteration in the same name of the dict, it can't be done, or maybe I still don't know how to do it. Thank for your answer and if you have some insight about it, it would be awasome. – fega_zero Jan 30 '21 at 18:57
2

This is probably the easiest way for beginners. You might want to learn how to use lists:

>>> x = []
>>> for i in range(10):
    x.append('abc')

>>> print(x[0])
abc
>>> print(x[8])
abc
>>> print(x)
['abc', 'abc', 'abc', 'abc', 'abc', 'abc', 'abc', 'abc', 'abc', 'abc']

You can also use globals or locals:

>>> for i in range(10):
    globals()["x" + str(i)] = 'abc'
>>> x1
'abc'

Useful links:

  1. Data Structures
mrhallak
  • 1,138
  • 1
  • 12
  • 27