[Tutor] iterating over a changing list
eryksun
eryksun at gmail.com
Wed Oct 10 23:49:19 CEST 2012
On Wed, Oct 10, 2012 at 3:52 PM, Ed Owens <eowens0124 at gmx.com> wrote:
>
> import string
Why are you importing "string"? Most string functions one would need
are methods of str/unicode. Sometimes "string" is still required,
however.
> def add_element(items, point):
> items = items[:point+1][:] + [['new']] + items[point+1:]
> return items
items[:point+1][:] creates a copy of part of the list with the slice
[:point+1], and then it copies the copy with the slice [:].
Redundant operations aside, this is returning a new list object.
That's not going to work since the loop iterator is bound to the
original list. You can't rebind a listiterator in the middle of a for
loop.
Also, generally avoid mutating a list while iterating over it.
listiterator is just incrementing an index, so modifying the size of
the list can produce nonsense (e.g. if you remove the current item,
the next item will be skipped). Instead, create an empty list and
append() to it.
More information about the Tutor
mailing list