L[:]

Terry Reedy tjreedy at udel.edu
Mon Jan 13 15:23:17 EST 2014


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




More information about the Python-list mailing list