Why does list append inside a loop duplicate the last element?

3 days ago 12
ARTICLE AD BOX

I’m trying to append values to a list inside a loop, but instead of getting different values, the last value keeps getting duplicated.

Here is a simplified version of my code:

result = []

temp = []

for i in range(5):

temp.append(i) result.append(temp)

I expected result to be:

[[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4]]

But instead I get:

[[0, 1, 2, 3, 4],

[0, 1, 2, 3, 4],

[0, 1, 2, 3, 4],

[0, 1, 2, 3, 4],

[0, 1, 2, 3, 4]]

Read Entire Article