Python list.append output values differ from list.extend -
saw question on site piece of python code driving nuts. small, straightforward-looking piece of code, looked @ it, figured out trying do, ran on local system, , discovered why driving original questioner nuts. hoping here can me understand what's going on.
the code seems straightforward "ask user 3 values (x,y,z) , sum (n); iterate values find tuples sum n, , add tuples list." solution. outputs is, instead of tuples sum n, list of tuples count of equal count of tuples sum n, contents of "[x,y,z]". trying wrap head around this, changed append call extend call (knowing un-list added tuples), see if behavior changed @ all. expected same output, "x,y,z,x,y,z..." repeatedly, instead of "[x,y,z],[x,y,z]" repeatedly, because read , understand python documentation, that's difference between append , extend on lists. got instead when used extend correct values of tuples summed n, broken out of tuple form extend.
here's problem code:
my = [] x = 3 y = 5 z = 7 n = 11 part = [0,0,0] in range(x+1): part[0] = j in range(y+1): part[1] = j k in range(z+1): part[2] = k if sum(part) == n: my.append(part) print(my)
and output:
[[3, 5, 7], [3, 5, 7], [3, 5, 7], [3, 5, 7], [3, 5, 7], [3, 5, 7], [3, 5, 7], [3, 5, 7], [3, 5, 7], [3, 5, 7], [3, 5, 7], [3, 5, 7], [3, 5, 7], [3, 5, 7]]
and here's extend output:
[0, 4, 7, 0, 5, 6, 1, 3, 7, 1, 4, 6, 1, 5, 5, 2, 2, 7, 2, 3, 6, 2, 4, 5, 2, 5, 4, 3, 1, 7, 3, 2, 6, 3, 3, 5, 3, 4, 4, 3, 5, 3]
and extend code:
my = [] x = 3 y = 5 z = 7 n = 11 part = [0,0,0] in range(x+1): part[0] = j in range(y+1): part[1] = j k in range(z+1): part[2] = k if sum(part) == n: my.extend(part) print(my)
any light shed on appreciated. i've dug around while on google , several q&a sites, , things found regarding python append/extend deltas things don't seem have relevance issue.
{edit: environment detail}
also, ran in both python 2.7.10 , python 3.4.3 (cygwin, under windows 10 home) same results.
extend
adds items parameter list list object making call. more like, dump objects 1 list without emptying former.
append
on other hand, appends; nothing more. therefore, appending list object list existing reference appended list damage - in case. after list has been appended, part
still holds reference list (since you're modifying in place), you're modifying , (re-)appending same list object every time.
you can prevent either building new list @ start of each parent iteration of append case.
or appending copy of part
list:
my.append(part[:]) my.append(list(part)) my.append(part.copy()) # python 3
this append list has no other existing reference outside new parent list.
Comments
Post a Comment