L[:]
Albert-Jan Roskam
fomcl at yahoo.com
Tue Jan 14 05:42:07 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.
====> Hi, first, thank you all for your replies -much appreciated!
Terry, this would be making a shallow copy, right? If so, then "list(L)" is slightly nicer IMHO, but that's probably a matter of taste (however, I don't like copy.copy, even though that's perhaps most clear --oh well nitpicking ;-)
I also found that item assignment ([1] below) is much faster than using the more standard (I think) .append ([2]).
# [1]
for idx,item in enumerate(L[:]):
if some_condition:
L[idx] = foobarify(item)
# [2]
L2 = []
for idx,item in enumerate(L):
if some_condition:
L2.append(foobarify(item))
else:
L2.append(item)
More information about the Python-list
mailing list