non-copy slices

Ethan Furman ethan at stoneleaf.us
Thu Nov 19 09:44:19 EST 2009


Please don't top post.  :)

tbourden at doc.ic.ac.uk wrote:
> On Thu, Nov 19, 2009 at 3:00 AM, Rami Chowdhury 
> <rami.chowdhury at gmail.com <mailto:rami.chowdhury at gmail.com>> wrote:
> 
>     I'm not sure you're understanding the point others have been making. A
>     list item is merely another reference to an existing object -- it
>     doesn't copy the object in any way.
> 
> No I'm well aware that there is no deep copy of the objects and the 
> lists only keep references to the objects and in essence they have the 
> same objects in there. But this doesn't mean they are the same list. 
> Modifications to slices are not written back to the original list.
> 
> x = range(5)
> y = x[1:3]
> y[0] = 13
> x[1] == y[0]  --> False
> 
> Of course if I modify the object in the slice then the original list 
> will see the change, but this is not what I was saying. Second and more 
> importantly it's the performance penalty from allocating a large number 
> of lists produced from the slices and the copy of the references. islice 
> does not have this penalty, it should only instantiate a small object 
> that iterates on the original list.
> 
> Themis

So "shallow copy" == "new label created for existing object".

So is your desired behavior to write back to the original list if your 
sub-list is modified?  In other words, you are creating a window onto an 
existing list?  If not, what would happen when a sublist element was 
modified (or deleted, or appended, or ...)?

~Ethan~



More information about the Python-list mailing list