1

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
  • 387
  • 4
  • 19

5 Answers5

6

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
  • 4,028
  • 2
  • 20
  • 30
Israel-abebe
  • 538
  • 1
  • 4
  • 20
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
  • 4,028
  • 2
  • 20
  • 30
Anton vBR
  • 18,287
  • 5
  • 40
  • 46
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,830
  • 4
  • 53
  • 88
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
  • 4,759
  • 14
  • 54
  • 76
1

You should better use dictionary for this:

var_dict = {
    'var'+str(i): i
        for i in range(10)
}
var_dict['var0']
Rahul
  • 10,830
  • 4
  • 53
  • 88