[Tutor] In-place changes on loops

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Feb 3 20:18:36 CET 2005




> But let's change it to what I think you were thinking of:
>
> ###
> def lstrip(string, chars):
>     scratchspace = list(string)       ## get a mutable list of characters
>     for x in scratchspace:
>         if x in chars:
>             scratchspace[i] = ''
>     return ''.join(scratchspace)
> ###
>
> This works fine.


Hi Sandip,

Doh.  I hate people who make blanket assertions like that without even
doing a minimal test.  Even if it is myself.  *grin*



The code above is just broken, since there is no index 'i'.  Let me try to
fix it.

###
def lstrip(string, chars):
    scratchspace = list(string)       ## get a mutable list of characters
    for (i, x) in enumerate(scratchspace):
        if x in chars:
            scratchspace[i] = ''
    return ''.join(scratchspace)
###



I'm not going to make the same mistake twice: we're going to test this
sucker.  *grin*

###
>>> lstrip("hello world", "he")
'llo world'
>>> lstrip("hello world", "eh")
'llo world'
###



Everything looks peachy... except:

###
>>> lstrip("hello world", "aeiou")
'hll wrld'
###

Ah!  That's not right either!


Ok, one more time:

###
def lstrip(string, chars):
    scratchspace = list(string)       ## get a mutable list of characters
    for (i, x) in enumerate(scratchspace):
        if x in chars:
            scratchspace[i] = ''
        else:
            break
    return ''.join(scratchspace)
###


Quick sanity check:

###
>>> lstrip("hello world", "eh")
'llo world'
>>> lstrip("hello world", "he")
'llo world'
>>> lstrip("hello world", "aeiou")
'hello world'
###


Finally.  *grin*


Anyway, I wanted to apologize; I should have tested my code.



More information about the Tutor mailing list