I am using Python version 3.7.5
I realized a bug in my code to transform some data, and I've done my best to create a minimum working example of the problem.
First, here is code that works as I expect it to:
a = ['foo','bar']
b = ['spam','eggs']
c = {'glue':a, 'dill':b}
for i in range(23,25):
c['dill'] = c['dill'] + [i]
print(b)
print(c)
# ['spam', 'eggs']
# {'glue': ['foo', 'bar'], 'dill': ['spam', 'eggs', 23, 24]}
Namely, the code in the for
loop does not affect the value of b
.
But when I switch to using the increment operator, this is no longer the case:
a = ['foo','bar']
b = ['spam','eggs']
c = {'glue':a, 'dill':b}
for i in range(23,25):
c['dill'] += [i]
print(b)
print(c)
# ['spam', 'eggs', 23, 24]
# {'glue': ['foo', 'bar'], 'dill': ['spam', 'eggs', 23, 24]}
In using Python, I had always been under the impression that:
a += 1
anda = a + 1
did exactly the same thing- when a variable is defined based on another variable (
b=a
), subsequent changes to the new variable (b=f(b)
) would not affect the original variable
The examples above seems to violate both of those assumptions. What is going on?