0

How can I create varying variable name?

like i am iterating in a loop say from 0 to 100.

I need to create different variable in each iteration and assign some values to it. an example

for i in range(0,100):
   'var'+i=i

Doesnot seems valid. I want to create variables in each iteration like var0,var1 etc and should be able to access it with that names. Can some one suggest me a solution

syam
  • 367
  • 3
  • 17

5 Answers5

2

To solve this, you can try something like this:

for x in range(0, 9):
    globals()['var%s' % x] = x

print var5

The globals() function produces a list-like series of values, which can be indexed using the typical l[i] syntax.

"var%s" % x uses the %s syntax to create a template that allows you to populate the var string with various values.

E. Ducateme
  • 3,643
  • 2
  • 17
  • 29
Israel-abebe
  • 466
  • 1
  • 3
  • 17
2

Unless there is a strong reason to create multiple variables on the fly, it is normally in these situations to put things in a list of some sort, or a dictionary:

mydict = {'var{}'.format(i):i for i in range(1,101)}

Now access values with:

mydict["var1"] # returns 1
mydict.get("var1") # returns 1
mydict.get("var101") # returns None
E. Ducateme
  • 3,643
  • 2
  • 17
  • 29
Anton vBR
  • 16,833
  • 3
  • 36
  • 44
1

I don't like your Idea but yeah you can do it in python:

for i in range(0,100):
    exec('var{i} = {i}'.format(i=i))
Rahul
  • 10,000
  • 4
  • 47
  • 84
1

I wouldn't recommend doing this using varying variable names. Instead, you could put everything into a list and you would still be able to access each value independently. For example, you could do:

var = []
for i in range(100):
    var.append(i)

Then you can access any element from that list like so:

var[33]

This would return the number 33.

If you really did want each to be its own variable, you could use exec as others have noted.

jss367
  • 3,809
  • 7
  • 47
  • 70
1

You should better use dictionary for this:

var_dict = {
    'var'+str(i): i
        for i in range(10)
}
var_dict['var0']
Rahul
  • 10,000
  • 4
  • 47
  • 84