List of lists surprising behaviour

Stephen Hansen me+list/python at ixokai.io
Fri Jun 18 12:47:38 EDT 2010


On 6/18/10 8:40 AM, bart.c wrote:
> I suppose there are pros and cons to both approaches; copying all the time
> at least avoids some of the odd effects and inconsistencies you get using
> Python:

What inconsistencies? All your examples are perfectly consistent. Its
just consistent to different ideals. Python never copies implicitly; and
every object you create has a concrete identity in and of itself,
utterly separate from its potential equality.

> a1=[1,2,3]
> a1.append(a1)

The "a1" object is a distinct object unto itself; you are appending said
distinct object onto the end of itself. Entirely doable, even if you
don't usually want to. Recursive, but doable if that's what you want. If
you wished to append a copy, you must-- as always, consistently--
explicitly copy it.

I.e.,

a1.append(a1[:])

> a2=[1,2,3]
> b=[1,2,3]
> a2.append(b)

a2 is a distinct object from b; that the two objects are equal means
nothing. So you're appending an object to the end of a2 which happens to
be equal to it.

> a3=[1,2,3]
> a3.append([1,2,3])

This is just another way of writing the previous example; that in one
you are naming the object [1,2,3] and in the other you are not, doesn't
mean anything. A named vs unnamed object in Python behaves exactly the same.

> print ("a1 = ",a1)
> print ("a2 = ",a2)
> print ("a3 = ",a3)
> 
> Here, a1 ends up with a different result from a2, a3, even though the same
> value is being appended to the same list of numbers in each case. 

There's the rub: the VALUE is not being appended. The *actual object* is.

Consider:

>>> print a1 is a2
False

> And it
> might sometimes bite you in the arse as the OP demonstrated:
> 
> L=[1,2,3]
> M=[0,1]
> M.append(L)
> 
> print (M)     # output: [0, 1, [1, 2, 3]]
> 
> L[1]=31416
> 
> print (M)     # output: [0, 1, [1, 31416, 3]], yikes!

That might bite you on your arse if you think Python implicitly copies;
but since the rule is very simple -- it /never/ implicitly copies -- and
that it objects are discrete entities and not just names of certain
values, it more likely then not will be beneficial to you quite often
down the road. You'll -want- that to be how things work. Eventually.
When you learn more Python.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 487 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20100618/424f44b2/attachment-0001.sig>


More information about the Python-list mailing list