0

Is there any way to declare a variable name string with number while running a loop? How can I do that? For example given n1, n2, n3..., n1 has to store i+l value(n("string") with i("number") = n1) then n2 has to stored i+l value of iterated loop.....etc

i=0
l=1
K=range(2,10)
for i in K:
    print i
    #how to declare a variable name by concatenating string and number
    print '--------',l+i
    #print n1,n2.....etc
b4hand
  • 9,550
  • 4
  • 44
  • 49
  • Is this what you're trying to do: http://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables-in-python-via-to-a-while-loop ? – Parzival Sep 19 '13 at 02:37
  • 1
    Do not try to dynamically name variables. Use a `dict` if you have key-value pairs. – roippi Sep 19 '13 at 02:41

2 Answers2

0

Use a list like such...

n = []
for i in k:
    n.append(some_value)

then, instead of n1, you could access each variable with n[0], n[1]...

(you could also use a dictionary if you needed more flexibility on index numbers...

n = {}
for i in k:
    n[i] = some_value
Paul Becotte
  • 9,767
  • 3
  • 34
  • 42
0

Despite the fact that this is a Very Bad Idea, yes, you can do it.

def fun():
    name = "n"
    for i in range(4):
        exec '%s%d = %d'%(name, i, 2**i)
    print n0
    print n1
    print n2
    print n3

fun()
Robᵩ
  • 163,533
  • 20
  • 239
  • 308