Reputation: 131
I want to write a for loop that iterates over variables and updates their values. for example:
x = 1
y = 1
for varNames in [x,y]:
varNames = varNames + 1
print(x)
print(y)
Here I want to have the function print the value 2 for both x and y, but my output is still 1. It is because the varNames variable gets updated but not x and y. How do I update the values for actual variable names x and y?
Thanks for the help!
Upvotes: 0
Views: 518
Reputation: 42139
At the global level (i.e. not within a function) you could do this using the globals() function.
x = 1
y = 1
for varName in ["x","y"]:
globals()[varName] += 1
print(x) # 2
print(y) # 2
However, if you need to do that kind of thing in your program, you might want to learn more about lists and dictionaries which would be the preferred approach.
data = dict()
data["x"] = 1
data["y"] = 1
for varName in data:
data[varName] = data[varName] + 1
print(data["x"]) # 2
print(data["y"]) # 2
Upvotes: 4
Reputation: 37
You can just make a list containing the variables and then you can iterate over them and print each object of the list.
x = 1
y = 3
mylist=[x,y]
for index in mylist:
print(index)
Upvotes: -1