0

I am just practicing python code and found a strange phenomenon while appending a list to another list. Please take a look at the code:

inside = []
outside = []

for i in range(10):
    inside.append(i)
    outside.append(inside)

print(outside)

It outputs :

[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]

But shouldn't output be something like this:

[[0],[0, 1],[0, 1, 2],[0, 1, 2, 3],[0, 1, 2, 3, 4],[0, 1, 2, 3, 4, 5],[0, 1, 2, 3, 4, 5, 6],[0, 1, 2, 3, 4, 5, 6, 7],[0, 1, 2, 3, 4, 5, 6, 7, 8],[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]

I am confused as to where am I getting it wrong. Please help.

Gsbansal10
  • 303
  • 5
  • 12

1 Answers1

5

This is because you tell Python that you append the array with name "inside" to outside. This means, that the array outside looks like this:

outside = [inside, inside, inside, inside, inside, inside, inside, inside, inside, inside]

This happens because Python appends a so called pointer to the array of outside, not the actual content of the array itself.

DWuest
  • 619
  • 1
  • 7
  • 18