Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you update the values of multiple variables in a loop in Python?

Tags:

python

scope

I would like to do something like the following:

x = 1
y = 2
z = 3

l = [x,y,z]

for variable in l:
    variable += 2

print x
print y
print z

Unfortunately, when I print x,y and z after this block, the values have remained at 1,2 and 3 respectively.

I have looked at this related question, but the solution there doesn't solve my problem.

Is there a neat and efficient way to perform the same action to multiple variables like I have tried to above?

P.S. I am using Python 2.6

like image 338
Punson Avatar asked Dec 09 '14 04:12

Punson


People also ask

How do you update a value in a for-loop in Python?

A for-loop uses an iterator over the range, so you can have the ability to change the loop variable. Consider using a while-loop instead. That way, you can update the line index directly.

How do you change multiple variables in Python?

You can assign multiple values to multiple variables by separating variables and values with commas , . You can assign to more than three variables. It is also possible to assign to different types. If there is one variable on the left side, it is assigned as a tuple.

How do you use a loop with multiple variables?

Yes, I can declare multiple variables in a for-loop. And you, too, can now declare multiple variables, in a for-loop, as follows: Just separate the multiple variables in the initialization statement with commas. Do not forget to end the complete initialization statement with a semicolon.


1 Answers

You cant change x,y,z like this. x,y,z are integers and they are immutable. You need to make new variables.

x, y, z = (v + 2 for v in l)
like image 198
Marcin Avatar answered Sep 25 '22 23:09

Marcin