question about a program

Steven D'Aprano steve at
Sat Oct 9 04:01:32 CEST 2010

On Thu, 07 Oct 2010 17:39:51 -0700, Logan Butler wrote:

> question about an assignment:
>>>> places("home sweet home is here",' ')
> [4, 10, 15, 18]
> this is my code:
> def places(x, y):
>     return [x.index(y) for v in x if (v == y)]
> so far I'm only getting
> [4, 4, 4, 4]
> so the first value is correct, it is just not iterating on to the next
> three items it needs to

Not every tool is a hammer, not every list builder needs to be a list 
comp, and not every function needs to be a one-liner. The simplest way to 
deal with this is to do an explicit loop.

Also, your names "x" and "y" are misleading. It is conventional to expect 
x and y to be numeric values, so it is best to pick more descriptive 

def places(s, sub):
    """Return indexes into string s where non-overlapping copies 
    of substring sub is found, or [-1] if not found at all.
    n = len(sub)
    start = 0
    indexes = []
        while True:
            i = s.index(sub, start)
            start = i + n
    except ValueError:
        if not indexes: indexes = [-1]
    return indexes


More information about the Python-list mailing list