modifying mutable list elements in a for loop
Roy Smith
roy at panix.com
Wed May 26 10:17:37 EDT 2004
Michael Chermside <mcherm at mcherm.com> wrote:
> >>> alist = range(10)
> >>> for x in alist:
> ... alist.remove(x)
> ...
> >>> alist
> [1, 3, 5, 7, 9]
>
> This behavior is perfectly well defined. (Think about it. Now think
> about it again. Got it?) But you have to admit that it's confusing
> to beginners, so the Tutorial strongly recomends against it.
It's confusing to non-beginners too. I've been using Python for 7 years
now. While I don't spend a lot of time delving into the esoterica of
the language, I think I've got a pretty good handle on how it works.
I think I understand what's going on in the loop, but there's a
difference between being able to understand why it's doing something vs.
being able to look at a piece of code and predict what it's going to do.
I don't think I would have been able to do that with this code.
So, my recommendation is to stay away from tricky things like this. The
same thing could have been done with:
>>> temp = range (10)
>>> alist = temp [1::2]
>>> alist
[1, 3, 5, 7, 9]
or for that matter:
>>> range (1, 10, 2)
[1, 3, 5, 7, 9]
but I suspect the point of the example was not how to create such a list
from scratch, but how to get every other element of an existing list.
Never try to be fancy. Someday, somebody's going to have to read your
code and they'll curse you for it. That somebody might even be you.
More information about the Python-list
mailing list