0

I've encountered what I think is odd behaviour for the append() function, and I've managed to duplicate it in the following simplified code:

plugh1 = []
plugh2 = []
n = 0
while n <= 4:
    plugh1.append(n)
    plugh2.append(plugh1)
    n = n+1
print plugh1
print plugh2

I would expect this code to result in:

plugh1 = [1, 2, 3, 4]
plugh2 = [[1], [1, 2], [1, 2, 3, ], [1, 2, 3, 4]]

but the actual result is:

plugh1 = [1, 2, 3, 4]
plugh2 = [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]

As the loop runs, each time all array elements are replaced with the value of plugh1.

There is a similar question on SO but the solution seems related to nesting functions and defining a variable outside of those calls. This is much simpler I think. What am I missing?

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
rc plitt
  • 23
  • 5

3 Answers3

2

When you do

plugh2.append(plugh1)

you are actually appending a reference to the first list, not the list as it currently is. Therefore the next time you do

plugh1.append(n)

you are changing the contents inside plugh2, as well.

You could copy the list like so, so that it doesn't change afterwards.

plugh2.append(plugh1[:])
Elle
  • 3,695
  • 1
  • 17
  • 31
1

The reason this occurs is that you are not copying the list itself, but only the reference to the list. Try running:

print(pligh2[0] is pligh2[1])
#: True

Each element in the list "is" every other element because they are all the same objects.

If you want to copy this lists themselves, try:

plugh2.append(plugh1[:])
# or
plugh2.append(plugh1.copy())
SCB
  • 5,821
  • 1
  • 34
  • 43
0

This:

plugh2.append(plugh1)

Appends a reference to plugh1, not a copy. This means future updates are reflected in plugh2. If you need a copy, see here: https://docs.python.org/2/library/copy.html

John Zwinck
  • 239,568
  • 38
  • 324
  • 436