Terry Carroll wrote:
On Fri, 14 Jan 2005, Chad Crabtree wrote:
class _macroString(object): def __init__(self,s): self.macro=s self.list=self.macro.split("\n") for n,v in enumerate(self.list): self.list[n]=v+'\n'
Is this for loop a safe technique, where the list you're enumerating over in the for statement is the same as the one being updated in the loop body? I always avoid things like that.
In this case it should be safe. This changes the string at each index in the list, but it doesn't change the length or ordering of the list. That's where the problems come in, because the for loop doesn't know that the list "shape" has changed.
But your caution is generally a good idea. :) I'd have probably written the above as:
self.list = [line+'\n' for line in self.list]
Well, actually, I'd have avoided saving the intermediary state and simply done all the list processing at once:
self.list = [line+'\n' for line in self.macro.split('\n')]
Either way, though, I'm creating a new list rather than modifying the old list in-place, which avoids the risk of accidentally changing the list's "shape" and throwing off the loop.
Jeff Shannon Technician/Programmer Credit International
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor