4

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
13
  • I think you'll have to do it manually. Here a, b, c are called by reference, therefore, the update only exists for the local variable v and not a, b, c Commented Sep 1, 2020 at 6:38
  • 2
    It's not really clear to me what you'd like to achieve, why the for loop? Commented Sep 1, 2020 at 6:39
  • @CosmosZhu What do you mean by called by reference? I'm not familiar with this and googling just makes me more confused. Commented Sep 1, 2020 at 6:39
  • @Cosmos547 Simply it means that during the for loop the operations do not apply to the original variable. Commented Sep 1, 2020 at 6:40
  • 1
    You're literally assigning to the variable v, that indeed won't change the variables a, b nor c. 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. Commented Sep 1, 2020 at 6:41

2 Answers 2

6

Try this:

a, b, c = [v+1 for v in (a,b,c)]
Sign up to request clarification or add additional context in comments.

Comments

3

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:

  1. Easy to perform an operation on all of them (like updating, printing, saving).
  2. Doesn't litter your code/namespace with an abundance of variables.
  3. 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.