Testing if an index is in a slice

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Jan 4 10:52:49 CET 2009

On Sat, 03 Jan 2009 14:53:12 -0800, Bryan Olson wrote about testing 
whether or not an index is in a slice:

> I'm leaning towards mmanns' idea that this should be built in.

What's the use-case for it?

> Handling 
> all the cases is remarkably tricky. Here's a verbose version, with a 
> little test:

[snip code]

Here's a less verbose version which passes your test cases:

def inslice(index, slc, len):
    """Return True if index would be part of slice slc of a 
    sequence of length len, otherwise return False.
    start, stop, stride = slc.indices(len)
    if stride < 0:
        return (start >= index > stop) and ((start-index) % -stride == 0)
        return (start <= index < stop) and ((index-start) % stride == 0)

(Hint: help(slice) is your friend.)


More information about the Python-list mailing list