Newbie looking for feedback
Alex Martelli
aleaxit at yahoo.com
Fri Sep 15 18:28:47 EDT 2000
"DaffyDuckMW" <daffyduckmw at my-deja.com> wrote in message
news:8ptbi1$qsv$1 at nnrp1.deja.com...
[snip]
> Ok, this is a little off the original subject but I'm curious so I'll
> ask it anyway. In the for line, the syntax "for x in lines[:]:" is
> used. I understand that the "[:]" provides a slice that includes the
> whole list and that this syntax can be used to basically obtain a copy
> of the list (right?). But in similar situations so far I've just used
Right.
> the syntax "for x in lines:". What is the advantage to adding the
> "[:]"? Does this affect performance, or accuracy? Also, does this
> affect what lines get processed if you mess with the list inside the
> loop?
Performance is better if you avoid the copy. However, the
copy is typically needed IF you're mutating the list within
the loop. For example:
>>> alist=range(10)
>>> for x in alist:
if x%3 == 0: alist.append(x+1)
print x,
0 1 2 3 4 5 6 7 8 9 1 4 7 10
>>> blist=range(10)
>>> for x in blist[:]:
if x%3 == 0: blist.append(x+1)
print x,
0 1 2 3 4 5 6 7 8 9
The second behavior is normally what one desires (the first
may not converge or give surprising results, depending on
details, though here it was chosen to converge!-). Thus, the
copy is normally a good thing if the list is going to be
mutated in the loop's body. No need for it if such mutation
is not present, though (only a certain runtime cost, though
probably not a terrible one).
Alex
More information about the Python-list
mailing list