1

I'm working on python program and i want something like this:

for i in range(1,n+1):
    var(a+str(i)) = input()
    #do something

So that variables are a1,a2,a3,etc. Can this be done, and how?

3
  • 1
    Why do you want that? Use a dict instead! And why was this question upvoted? For what reason? Commented Dec 22, 2012 at 8:18
  • You should get acquainted with the idea of zero-based numbering. The need to go through contortions like range(1,n+1) instead of range(n) should alert you to the fact that you're doing something wrong. Commented Dec 22, 2012 at 8:27
  • I need 'i' on multiple places, so I'd have to put (i+1) everywhere else. So range(1,n+1) makes the code shorter in this case... Commented Dec 22, 2012 at 8:36

1 Answer 1

4

You don't want to do that, trust me. You want to use a dictionary

vars = {}
for i in range(1,n+1):
    vars[i] = input()
    #do something

or, since all the numbers are sequential in your special case, a list:

vars = [None]  #  initialize vars[0] with None
for i in range(n):
    vars.append(input())
    #do something

Now you can access your variables like vars[2], vars[5] etc.

Sign up to request clarification or add additional context in comments.

1 Comment

(Of course, vars is a terrible name for a variable - you should use a meaningful name instead. This is just meant as an example.)

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.