5
votes

I have some logic which I need to repeat 6 times. Result is stored in variable at the end, but I need variable name to be something as data1, data2, data3, etc. So if I have:

for x in range(0, 3):
   ...some logic...
   data = result

How can I get data variable named as data1, data2 etc based on the loop number?

1
use a dictionary instead - MattDMo
data = [fn(x) for x in range(3)] - Hugh Bothwell

1 Answers

8
votes

you can use dictionary like this: examples

>>> a = ['hello', 'banana', 'apple']
>>> my_dict = {}
>>> for x in range(len(a)):
...     my_dict[x] = a[x]
... 
>>> my_dict
{0: 'hello', 1: 'banana', 2: 'apple'}

>>> my_dict[1]
'banana'