Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #63669 > unrolled thread

Re: L[:]

Started byNed Batchelder <ned@nedbatchelder.com>
First post2014-01-10 17:03 -0500
Last post2014-01-10 17:03 -0500
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: L[:] Ned Batchelder <ned@nedbatchelder.com> - 2014-01-10 17:03 -0500

#63669 — Re: L[:]

FromNed Batchelder <ned@nedbatchelder.com>
Date2014-01-10 17:03 -0500
SubjectRe: L[:]
Message-ID<mailman.5308.1389391443.18130.python-list@python.org>
On 1/10/14 12:38 PM, Albert-Jan Roskam wrote:
> In Python Cookbook, one of the authors (I forgot who) consistently used the "L[:]" idiom like below. If the second line simply starts with "L =" (so no "[:]") only the name "L" would be rebound, not the underlying object. That was the authorÅ› explanation as far as I can remember. I do not get that. Why is the "L[:]" idiom more memory-efficient here? How could the increased efficiency be demonstrated?
>
> #Python 2.7.3 (default, Sep 26 2013, 16:38:10) [GCC 4.7.2] on linux2
>>>> L = [x ** 2 for x in range(10)]
>>>> L[:] = ["foo_" + str(x) for x in L]
>

I'm not sure there is a memory efficiency argument to make here.  The 
big difference is that the first line make L refer to a completely new 
list, while the second line replaces the contents of an existing list. 
This makes a big difference if there are other names referring to the list:

 >>> L = [1, 2, 3, 4]
 >>> L2 = L
 >>> L[:] = []
 >>> print L2
[]

 >>> L = [1, 2, 3, 4]
 >>> L2 = L
 >>> L = []
 >>> print L2
[1, 2, 3, 4]

Names and values in Python can be confusing.  Here's an explanation of 
the mechanics: http://nedbatchelder.com/text/names.html

HTH,

--Ned.

>
> Thanks!
>
>
> Regards,
>
> Albert-Jan



-- 
Ned Batchelder, http://nedbatchelder.com

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web