0

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

Can anyone give me an idea?

At the time of creation I also need to be able to assign values to them.

That's where I'm getting syntax error.

2
  • Why don't you use an array for that? Commented Dec 17, 2008 at 13:50
  • Posting the code that raises SyntaxError would be a good idea. Commented Dec 17, 2008 at 14:03

4 Answers 4

13

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

a = 10*[0]
a[0], a[1], a[2], a[9]
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

2

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.

Comments

-1

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.

3 Comments

(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.
exec is not a function (in 2.x); you don't need the parentheses around it.
@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 ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.