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?
Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.
Answer. In Python, a for loop variable does not have to be initialized beforehand. This is because of how Python for loops work.
To summarize: Python lets you create variables simply by assigning a value to the variable, without the need to declare the variable upfront. The value assigned to a variable determines the variable type.
You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value. It is also possible to assign another value into one after assigning the same value.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With