6

I'm trying to create several arrays in a loop and have access to them further on. I don't understand why I can modify and print them within the loop but outside it says the variable doesn't exist.

for i in range (0,3):
    a_i=[i]
    a_i.append(i+1)
    print a_i
print a_1

Is there anyone who can give me a suggestion on how to fix the problem?

4
  • Have a read through en.wikipedia.org/wiki/Scope_(computer_science) Commented Nov 18, 2012 at 15:14
  • 2
    You have not defined a_1, only a_i. Commented Nov 18, 2012 at 15:15
  • 5
    There's no reason to downvote someone because their code is wrong. Their code being wrong is why they're asking the question. Commented Nov 18, 2012 at 15:17
  • @flabons Welcome to StackOverflow! Let me inform you that is not a forum, it's a Q&A site. If you want to discuss an answer, use "add comment". If you want to provide additional details, edit your question, we'll notice. Only use "Answer" when you're providing a solution to a question. Commented Nov 18, 2012 at 15:35

1 Answer 1

8

Variables name are tokens used as-is, i.e. variables aren't expanded inside other variable names.

You can't expect a_i to be equal to a_1 if i == 1.

For that, use arrays or dictionaries.

a = {}
for i in range (0,3):
    a[i] = [i]
    a[i].append(i+1)
    print a[i]
print a
print a[1]
Sign up to request clarification or add additional context in comments.

Comments

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.