Skip to content Skip to sidebar Skip to footer

Python Append Behaviour Odd?

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 &

Solution 1:

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[:])

Solution 2:

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())

Solution 3:

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

Post a Comment for "Python Append Behaviour Odd?"