[Python-bugs-list] [ python-Bugs-455694 ] bug in list append, or list multiply?

noreply@sourceforge.net noreply@sourceforge.net
Tue, 28 Aug 2001 07:56:53 -0700


Bugs item #455694, was opened at 2001-08-27 01:15
You can respond by visiting: 
http://sourceforge.net/tracker/?func=detail&atid=105470&aid=455694&group_id=5470

Category: Documentation
Group: None
>Status: Closed
>Resolution: Fixed
Priority: 5
Submitted By: Nobody/Anonymous (nobody)
Assigned to: Fred L. Drake, Jr. (fdrake)
Summary: bug in list append, or list multiply?

Initial Comment:
Python 2.1.1 (Windows NT 4)

>>> x=6*[[]]
>>> x
[[], [], [], [], [], []]
>>> x[3].append(7)
>>> x
[[7], [7], [7], [7], [7], [7]]

But, I was expecting:

[[], [], [], [7], [], []]

So I then tried this:

>>> x=[[],[],[],[],[],[]] # instead of x=6*[[]]
>>> x[3].append(7)
>>> x
[[], [], [], [7], [], []]

And it worked.

----

I imagine what is happening is that 6*[[]] creates 6 pointers to the same empty list?  But, if so, 
the python docs (http://www.python.org/doc/current/lib/typesseq.html) imply otherwise:

s * n , n * s yields n _copies_ of s concatenated

Anyway, I'm confused.

----------------------------------------------------------------------

>Comment By: Fred L. Drake, Jr. (fdrake)
Date: 2001-08-28 07:56

Message:
Logged In: YES 
user_id=3066

Fixed in Doc/lib/libstdtypes.tex revision 1.68.

----------------------------------------------------------------------

Comment By: Tim Peters (tim_one)
Date: 2001-08-27 14:25

Message:
Logged In: YES 
user_id=31435

Changed to Doc and reassigned to Fred.  The docs may be 
clearer if they said "n shallow copies" instead of "n 
copies".

>>> s = [[]]
>>> from copy import copy
>>> x = copy(s) + copy(s) + copy(s)
>>> x
[[], [], []]
>>> x[1].append(7)
>>> x
[[7], [7], [7]]
>>>

That is, "s*n is n copies of s concatenated" is correct, 
but only if you have shallow copies in mind.

Anonymous, the effect you *want* can be gotten via

x = []
for i in range(6):
    x.append([])

or, in Python 2.0+ via

x = [[] for i in range(6)]

Doing

[O] * n

creates a list with n repetitions of O, i.e. exactly the 
same object n times, the same as [O, O, O, ...].  In

[[], []]

you create two distinct empty lists, but in

temp = []
[temp, temp]

you get a single empty list twice.  Same thing for

[[]] * n

----------------------------------------------------------------------

You can respond by visiting: 
http://sourceforge.net/tracker/?func=detail&atid=105470&aid=455694&group_id=5470