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
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.
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.
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.
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)
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