views:

228

answers:

4

I want to create varibales as a1,a2,a3,...a10. For that i used a for loop.As the variable in loop increments..i need var gettng created as above .

Can anyone give me an idea?

At the same time of creation i need to be able to assign to them

There i m gettng syntax error

+12  A: 

Usually, we use a list, not a bunch of individual variables.

a = 10*[0]
a[0], a[1], a[2], a[9]
S.Lott
A: 

You can use the exec function:

for i in range(0,10):
   exec("a%d=%d" % (i,i))

Not very pythonic way of doing things.

kgiannakakis
(I didn't downvote) This is correct, but it's not really helpful for a Python programmer wannabe. The questions hints at a need for guidance.
ΤΖΩΤΖΙΟΥ
it was helpful....but i faced a new problem.Need your help.
That recommendation is frightening.
Greg Hewgill
exec is not a function (in 2.x); you don't need the parentheses around it.
Martin v. Löwis
@Martin v. Löwis: putting them works in 2.5.2 ... Anyway the code solves the question, but I agree with ΤΖΩΤΖΙΟΥ, there should be also a 'pythonic' hint ;)
Andrea Ambu
+4  A: 

Following what S.Lott said, you can also use a dict, if you really nead unique names and that the order of the items is not important:

data = {}
for i in range(0, 10):
  data['a%d' % i] = i

>>>data
{'a1': 1, 'a0': 0, 'a3': 3, 'a2': 2, 'a5': 5, 'a4': 4, 'a7': 7, 'a6': 6, 'a9': 9, 'a8': 8}

I would add that this is very dangerous to automate variable creation like you want to do, as you might overwrite variables that could already exist.

Mapad
+2  A: 

globals() returns the global dictionary of variables:

for i in range(1,6):
    globals()["a%i" % i] = i

print a1, a2, a3, a4, a5      # -> 1 2 3 4 5

But frankly: I'd never do this, polluting the namespace automagically is harmful. I'd rather use a list or a dict.

Tim
Very cool. Wish I had thought of that.
vy32