Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to create new variables in for loops?

Tags:

python

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?

like image 429
flabons Avatar asked Nov 18 '12 15:11

flabons


People also ask

Can you create a variable in a for loop?

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.

Can you initialize a variable in a for loop Python?

Answer. In Python, a for loop variable does not have to be initialized beforehand. This is because of how Python for loops work.

Can you create new variables in Python?

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.

How do you create multiple variables in Python?

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.


1 Answers

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]
like image 127
Kos Avatar answered Sep 18 '22 16:09

Kos