Home > Blockchain >  Python: How to add an integer value to each variable in a list?
Python: How to add an integer value to each variable in a list?

Time:12-07

I have 4 variables that each have an integer value:

a = 1
b = 2
c = 3
d = 4

I then have a list of the 4 variables:

list = [a, b, c, d]

How can I increment the value of all four variables in the list at once?

This is what I've tried so far:

for i in range(len(list)):
    list[i]  = 1
    print(list)
    print(a)
    print(b)
    print(c)
    print(d)

And the list changed, but not the variables:

[2, 3, 4, 5]
1
2
3
4

How can I use the list to change the variables' values?

CodePudding user response:

You need to create new a, b, c, and d variables that refer to the new value because list doesn't point to the old ones.

l = [a, b, c, d]
[a, b, c, d] = [x   1 for x in l]

output:

> print(a, b, c, d)

2 3 4 5

CodePudding user response:

How can I use the list to change the variables' values?

You can't, Python does not have general-purpose "dependent values". The stuff that's in the list are copies of the variables (but not the variable's values, those are different). Meaning there is essentially no relation between the two.

In order to relate the two, you'd need an indirection of some sort e.g. make both variable and list store some sort of reference, like an intermediate list.

Python actually has special-purpose references, usually via proxy objects. For instance locals() and globals() represent the corresponding scopes and give read/write access to their variables:

>>> a = 1
>>> globals()['a'] = 2
>>> a
2
  • Related