Why Does Foo.Append(Bar) Affect All Elements in a List of Lists

Why does foo.append(bar) affect all elements in a list of lists?

It is because the list contains references to objects. Your list doesn't contain [[1 2 3] [1 2 3]], it is [<reference to b> <reference to b>].

When you change the object (by appending something to b), you are changing the object itself, not the list that contains the object.

To get the effect you desire, your list a must contain copies of b rather than references to b. To copy a list you can use the range [:]. For example:

>>> a = []
>>> b = [1]
>>> a.append(b[:])
>>> a.append(b[:])
>>> a[0].append(2)
>>> a[1].append(3)
>>> print a
[[1, 2], [1, 3]]

Value changes in new list impact previous list values, within a list of lists

The short answer to your question is using colon:

 combinations.append(combinations[0][:])

Why? The reason is that in python when you append a variable into your list, the variable is appended by its reference. In your example, it means that the two elements in the list are the same. They are pointing to the same address in the memory and if you modify either of them, both value will change as they are one and using the same chunk of memory.

If you want to copy the values of a variable, in your case, combinations[0], you need to use colons to make a copy of values and put them in another part of memory (it will occupy another chunk of memory with different address) In this case, you can modify them separately.

You can also take a look at this question and answer: python list by value not by reference

I hope this helps.

Python append behaviour odd?

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

List.append() changing all elements to the appended item

I believe the current list is simply copied multiple times into past. So you have multiple copies of the same list.

To fix: in the line past.append(current) (two lines below def Gen(x,y):), change it to past.append(current[:]).

The notation list[:] creates a copy of the list. Technically, you are creating a slice of the whole list.

By the way, a better solution would be to not use a global current variable :)



Related Topics



Leave a reply



Submit