Search code examples
pythonfor-loopvariable-assignment

Assignments in for loops


This is something I wish to ask on top of the question that is already discussed:

Assigning values to variables in a list using a loop

So the link above says it is not recommended to perform assignments in a for loop because doing so changes only the reference of those values and doesn't change the original variable.

For example, if I wish to add 1 to each variable:

p = 1
q = 2
r = 3

a = [p,q,r]

for i in a:
  i += 1 

print(p, q, r)

# returns 1 2 3

So this doesn't change p, q, and r, since the values added by one are assigned to 'i'. I inquired some people about a possible solution to this issue, and one suggested that I try the 'enumerate' function. So I did:

p = 1
q = 2
r = 3

a = [p,q,r]

for idx, val in enumerate(a):
  a[idx] = val + 1 


print(p, q, r)

# returns 1 2 3 

So it still doesn't work. Printing the list 'a' does return the list of values added by 1, but it still doesn't change the values assigned to p, q, and r, which is what I want.

So the only solution I currently have is to do the assignment for each variable manually:

p = 1
q = 2
r = 3

p += 1
q += 1
r += 1 

print(p, q, r)

# returns 2 3 4

However, in a hypothetical setting where there are more variables involved than 3, such as 50 variables where I wish to add 1 to each value assigned, doing it manually is going to be very demanding.

So my question is, is there a solution to this without doing it manually? How do we accomplish this using the for loop? Or, if the for loop doesn't work for this case, is there another way?


Solution

  • You can maintain a dictionary, where the keys are strings (the names variables that you originally had) and the values are the integers that they're assigned to.

    Then, you can do the following:

    data = {
        "p": 1,
        "q": 2,
        "r": 3
    }
    
    for item in data:
        data[item] += 1
    
    print(data)
    

    This outputs:

    {'p': 2, 'q': 3, 'r': 4}