Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update values in a for loop in python?

Tags:

python

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
like image 925
Cosmos547 Avatar asked Oct 16 '25 15:10

Cosmos547


2 Answers

Try this:

a, b, c = [v+1 for v in (a,b,c)]
like image 73
dimay Avatar answered Oct 19 '25 04:10

dimay


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.

like image 32
Wups Avatar answered Oct 19 '25 04:10

Wups



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!