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


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

Re: L[:]

Started byTerry Reedy <tjreedy@udel.edu>
First post2014-01-13 15:23 -0500
Last post2014-01-13 15:23 -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[:] Terry Reedy <tjreedy@udel.edu> - 2014-01-13 15:23 -0500

#63860 — Re: L[:]

FromTerry Reedy <tjreedy@udel.edu>
Date2014-01-13 15:23 -0500
SubjectRe: L[:]
Message-ID<mailman.5428.1389644615.18130.python-list@python.org>
On 1/13/2014 4:00 AM, Laszlo Nagy wrote:
>
>> Unless L is aliased, this is silly code.
> There is another use case. If you intend to modify a list within a for
> loop that goes over the same list, then you need to iterate over a copy.
> And this cannot be called an "alias" because it has no name:

for i in somelist: creates a second reference to somelist that somewhere 
in the loop code has a name, so it is effectively an 'alias'. The 
essential point is that there are two access paths to the same object.

> for idx,item in enumerate(L[:]):
>     # do something with L here, including modification

The copy is only needed in the above if one inserts or deletes. But if 
one inserts or deletes more than one item, one nearly always does better 
to iterate through the original and construct a new list with new items 
added and old items not copied.

-- 
Terry Jan Reedy

[toc] | [standalone]


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


csiph-web