1

By definition List.append(elem) adds a single element to the end of the list.

however, the result of the codes below does not follow the rule:

lista = []

listb = []

for i in "abc":

    lista.append(i)

    listb.append(lista)

print(listb)

The result is:

[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]

according the rule, the result should be

[['a'], ['a', 'b'], ['a', 'b', 'c']]

why is that? and how to get the second result?

Seanny123
  • 8,776
  • 13
  • 68
  • 124
wmw12344
  • 11
  • 1

5 Answers5

1

Because you don't append ['a'], ['a', 'b'] and ['a', 'b', 'c'] but the reference to lista three times. And lista gets changed so it shows list (a) three times as it is.

Bernhard
  • 1,253
  • 8
  • 18
1

You are appending only reference to listb to lista. To get a desired result, you need to add copy of listb to lista (in this case is simple list() enough):

lista = []    
listb = []

for i in "abc":    
    lista.append(i)    
    listb.append(list(lista))

print(listb)

Result:

[['a'], ['a', 'b'], ['a', 'b', 'c']]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1

Copy() will do the trick:

lista = []

listb = []

for i in "abc":

    lista.append(i)

    listb.append(lista.copy())

print(listb)

You were appending the reference of a to b, then manipulating a...

Pablo Henkowski
  • 197
  • 1
  • 6
  • `copy()` will only work in Python 3.3+. For lower version we can slice it `listb.append(lista[:])` – mad_ Jul 12 '18 at 19:47
0

This is because you are adding the entirety of lista to listb and not a single element of lista.

For every iteration in "abc" you append the entire lista.

ltd9938
  • 1,444
  • 1
  • 15
  • 29
0
  1. lista and listb are actually references to lists. I will call them variables.
  2. Append() is adding things to the value that the variable refers to which is the actual list; furthermore, only you have finished operations to the variable (lista in this case), the actual list will be fixed.
  3. So listb.append(lista) actually adds the references into listb and listb will have lista's reference here. Just as mentioned above, the value that listb refers to will be fixed after lista finishes its own operations and that's why listb will have the whole lista instead of part of lista.
  4. You can try to reverse the order of two append() operations and it will give you the same answer.
Brandon14
  • 1
  • 2
  • see [this answer](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) for more info on list variables storing by reference and how to achieve the desired behavior – csunday95 Jul 12 '18 at 20:50
  • 1
    I see what you said. I didn't write the solution to the desired behaviour. I agree with your link, either copy() or list() can do things; they actually do the deep clone. – Brandon14 Jul 12 '18 at 21:27