Passing a list into a list .append() method

Paul Kroeger news at prz-wugen.com
Tue Sep 9 03:12:49 EDT 2014


Hello,

I'm myself still learning Python, so others may please correct me, if
I'm wrong.

Consider the following sentence of your link "jeffknupp.com/...": 

"some_guy and first_names[0] both refer to the same object"

This is what is going on here.

Am Dienstag, den 09.09.2014, 05:50 +0000 schrieb JBB:
> [...]
> 
> for i,j in enumerate(zip(qq,rr)):
>     proc_file.append((blank_r))  # Add a row of blanks

At this point, the last "row" of "proc_file" and the variable "blank_r"
both refer to the list object [blank_r].

>     proc_file[i+2][1] = j[0]
>     proc_file[i+2][2] = j[1]

The object under "proc_file[...]" is changed now. This object is the
list object [blank_r]! So "proc_file[-1]" and "blank_r" both refer to
[blank_r] = ["", j[0], j[1], ""], which is added do the list object
[proc_file] at the beginning of the next iteration.

Thus, all entries of [proc_file] with index greater 1 are bound to
[blank_r], which is itself modified in each iteration to the
corresponding j:

proc_file[0] -> ["a", "b,", "c", "d"]
proc_file[1] -> ["A", "B,", "C", "D"]
proc_file[2] -> [blank_r]
proc_file[3] -> [blank_r]
proc_file[4] -> [blank_r]
proc_file[5] -> [blank_r]
...

Thus, printing proc_file will always print the values of the last j for
all rows greater than 1.

Maybe, this will help (although I think you got it already:

proc_file = []
proc_file = [['a','b','c','d']]
proc_file.append(['A','B','C','D'])
blank_r = ['','','','']

qq = ['aa','bb','cc','dd']
rr = ['inky', 'binky', 'pinky', 'clyde']

for i,j in enumerate(zip(qq,rr)):

    proc_file.append((blank_r))  # Add a row of blanks
    print "proc_file at loop entry:", proc_file
    print "current blank_r:", blank_r
    proc_file[i+2][1] = j[0]
    proc_file[i+2][2] = j[1]
    print "proc_file at loop end:", proc_file, "\n\n"

And maybe thinking of lists as objects and of variables "containing"
lists (somehow) as "pointers" may also help.

> [...] 2) What works as desired:
>     proc_file.append(list(blank_r))  # Change it to list(blank_r) and it works

The list() function returns a copy of [blank_r]. So with this code,
"proc_file[-1]" refers not the same list object as "blank_r". This leads
to the desired behaviour of your program.

> It looks like .append binds blank_r to proc_file in 1).  I change proc_file
> and blank_r changes along with it.  Should I expect this? [...]

I hope, the above helps to understand why this behaviour.is to be
expected.

So long,
Paul




More information about the Python-list mailing list