Need a bit of help with a list..

Alex Martelli aleaxit at yahoo.com
Sun Feb 12 18:34:11 EST 2006


rh0dium <steven.klass at gmail.com> wrote:
   ...
> Why doesn't this work as expected..  I expect that the the lines within
> the sections will get modified - permanently.  It is modifying them
> during the first section but they never get saved to the new values..
> Can anyone help me and even better explain why it's not working..
> 
>         for section in self.sections:
>             nidx = 0
>             for line in self.sections[section]:

>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.

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.

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

This still has several problems (crashes if there's a + at the end of
the last line, doesn't join properly if two successive lines both end
with +, possibly others since my code is NOT tested) but they're not
horribly hard to fix if they're indeed problems for you.


Alex



More information about the Python-list mailing list