Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #63670 > unrolled thread
| Started by | Terry Reedy <tjreedy@udel.edu> |
|---|---|
| First post | 2014-01-10 17:38 -0500 |
| Last post | 2014-01-11 16:34 +0000 |
| Articles | 2 — 2 participants |
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.
Re: L[:] Terry Reedy <tjreedy@udel.edu> - 2014-01-10 17:38 -0500
Re: L[:] Grant Edwards <invalid@invalid.invalid> - 2014-01-11 16:34 +0000
| From | Terry Reedy <tjreedy@udel.edu> |
|---|---|
| Date | 2014-01-10 17:38 -0500 |
| Subject | Re: L[:] |
| Message-ID | <mailman.5309.1389393544.18130.python-list@python.org> |
On 1/10/2014 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] Unless L is aliased, this is silly code. The list comp makes a new list object, so if L does not have aliases, it would be best to rebind 'L' to the existing list object instead of copying it. To do the replacement 'in place': L = [x ** 2 for x in range(10)] for i, n in enumerate(L): L[i] = "foo_" + str(n) print(L) >>> ['foo_0', 'foo_1', 'foo_4', 'foo_9', 'foo_16', 'foo_25', 'foo_36', 'foo_49', 'foo_64', 'foo_81'] -- Terry Jan Reedy
[toc] | [next] | [standalone]
| From | Grant Edwards <invalid@invalid.invalid> |
|---|---|
| Date | 2014-01-11 16:34 +0000 |
| Message-ID | <larrq2$8qh$1@reader1.panix.com> |
| In reply to | #63670 |
On 2014-01-10, Terry Reedy <tjreedy@udel.edu> wrote: > On 1/10/2014 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] > > Unless L is aliased, this is silly code. And if L _is_ aliaised, it's probably trying to be too clever and needs to be fixed. -- Grant
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.python
csiph-web