user230517 user230517 - 22 days ago 7
Python Question

why the new_list has to be put inside the for loop to prevent global change?

Would any one tell me the difference between these two blocks? I have hard time figuring out why the second one only changes the nested list locally, while the first changes it globally. it seems to me they do the same thing.

my_list = [ ]
new_list = [0, 0, 0 ]## outside the loop
for index in range(5):
my_list.append(new_list)
my_list[0][1] = 5
print(my_list)

## result
[[0, 5, 0], [0, 5, 0], [0, 5, 0], [0, 5, 0], [0, 5, 0]]


my_list = [ ]
for index in range(5):
new_list = [0, 0, 0 ] ## inside the loop
my_list.append(new_list)
my_list[0][1] = 5
print(my_list)
## result
[[0, 5, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

Answer

Because inside the for loop, new_list get's redefined, effectively refering to a different list object for every iteration.

Printing the ids for the second case reveals this:

print(*map(id, my_list))  # Notice the different ids
140609203176456 140609194670088 140609194608840 140609212158216 140609194670152

Outside the loop, you append the same list object, the same reference. Changes will be visible througout all references.

Printing the ids for this case shows the same id (i.e, same list) is present:

print(*map(id, my_list))  # same id.
140609194670088 140609194670088 140609194670088 140609194670088 140609194670088