Say I have a list of variables with the following values
a, b, c = 1, 2, 3
How can I update the value of a,b,c
in a for loop?
I've tried the following but it doesn't work.
for v in (a, b, c):
v = v + 1
The values for a,b,c
remains unchanged after the process
print(a, b, c)
# [1] 1 2 3
Try this:
a, b, c = [v+1 for v in (a,b,c)]
If you have many related variables, a good choice is to store them in a list
or dict
. This has many advantages over having many separate variables:
# example using a dict
# give them a meaningful name
counters = {"a": 1, "b": 2, "c": 3}
for key in counters:
counters[key] += 1
a,b,c = [v+1 for v in (a,b,c)]
This creates an intermediate list with the new values, assigns these to your variables and then throws away the list again. This is an unnecessary intermediate step, but not a big issue.
The real problem with this is, that you still have to write out every variable name twice. It's hardly an improvement over just writing a,b,c = a+1,b+1,c+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