Need a bit of help with a list..

rh0dium steven.klass at gmail.com
Mon Feb 13 09:58:11 EST 2006


Alex Martelli wrote:

> From this constuct I assume self.sections is a dict, in which case there
> may be better way to loop over the values in the dict; but that's an
> aside and does not affect your stated problem.  Rather, said problem is
> already shown in the next couple lines:
>
> >                 if re.match(r"^.*\+$",line):
> >                     line = line[:-1]
>
> A simple assignment _to a bare name_ (here, 'line') only ever affects
> that NAME itself - nothing else, and in particular not the object to
> which the name used to be bound before you re-bound it, not other names
> (or locations within a container) bound to the same object, and so on.

That's what I was thinking it was doing and a simple proof showed me
this..

> To affect some item, say the i-th one, of self.sections[section], you
> will need to assign something to self.sections[section][i].  You may
> give another and nicer name to the whole objects self.sections[section],
> but you will still need to assign to whatevername[i] to rebind the i-th
> item -- assign to an indexing, not to a bare name.
>
> There's another problem later in this inner loop:
>
> >                     del self.sections[section][nidx+1]
>
> ...don't alter the container you're directly looping on, for example by
> deleting some of its items: that will alter the semantics of the loop in
> way you most definitely don't want. I don't think it's biting you here,
> but in most cases it will indeed bite, and painfully.

Thanks so much for pointing this out - it explains some behaviour I was
seeing!!

> I would suggest restructuring your whole first nested loop, correcting
> other strangeness (which is innocuous) as we go, such as the strange re
> and the separate and identical increments of nidx along an if and an
> else branch.  For example, trying to stay as close as feasible to your
> original code, we might have:
>
>         for lines in self.sections.itervalues():
>             nidx = 0
>             while nidx<len(lines):
>                 line = lines[nidx]
>                 if line.endswith('+'):
>                     lines[nidx] = line[:-1] + " " + lines[nidx+1]
>                     del lines[nidx+1]
>                 nidx += 1
>

Ah - A couple new methods - Thanks so much for your insightful comments
and concerns.  I will take it from here - much appreciated!!




More information about the Python-list mailing list