[Tutor] Strange modulus problem
Michael P. Reilly
arcege@speakeasy.net
Sat, 13 Oct 2001 12:39:33 -0400
On Sat, Oct 13, 2001 at 11:24:27AM -0500, Chris Keelan wrote:
> On Thu, 11 Oct 2001, Kirby Urner wrote:
>
> > This has to do with iterating over the object you're
> > also modifying.
>
> When you explain it that way, it makes perfect sense! For some reason I
> didn't think that the 'for' iteration worked by index. Perhaps there was a
> little gnome who took all of the objects out of a list, laid them out on a
> table and picked them up, one-by-one saying "If I divide six by this, will my
> remainder be zero? Nope? Well throw it out then."
Also, instead of removing items, you can append items to a new list:
m = range(100)
l = []
for i in m:
if (i % 13) == 0:
l.append( i )
print l
[0, 13, 26, 39, 52, 65, 78, 91]
Then there is no need to create a copy of the list, which could be
expensive if the list is large, and not removing items from a list,
which you can see is problematic.
-Arcege
--
+----------------------------------+-----------------------------------+
| Michael P. Reilly | arcege@speakeasy.net |