Using lists or dicts
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:
- Easy to perform an operation on all of them (like updating, printing, saving).
- Doesn't litter your code/namespace with an abundance of variables.
- Better maintainable code: Less places to change, if you need to add/remove a variable.
Update values in a for loop
# example using a dict
# give them a meaningful name
counters = {"a": 1, "b": 2, "c": 3}
for key in counters:
counters[key] += 1
Comparing this to updating separate variables in a loop
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.
vand nota, b, cfor loop?v, that indeed won't change the variablesa,bnorc. You'd have to assign to the variable by name, but once you go there, you're usually on the wrong track. There are probably way better approaches to whatever problem you're trying to implement here that render this issue moot.