faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

16 of 17 people (94%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

Extended slicing

Jul 5th, 2000 09:58
Nathan Wallace, Hans Nowak, Snippet 2, Fredrik Lundh


"""
Packages: basic_datatypes
"""

"""
>Is extended slicing something new? I found some mention of it in the
>documentation (and a definition in the language reference) but no
>simple explanation... I think I basically understand it, but I can't
>seem to get (among other things) the ellipsis to work... (v1.5)
>
>(As in list[1,4,...,6] or something...)
>
>Am I using a too old Python, or am I doing something wrong?

[...]

>I've a problem with extended slicing in 1.5
>expressions like:
>>>> a=range(100)
>>>> print a[5:20:5]
>Simply don't work, the interpreter wants an integer index there.

extended slicing was developed for Numerical Python, and is
not supported by the standard sequence types.

[...]

> Does extended slicing work for built-in lists? What good is an 
> Ellipsis? Any working code?

The following sample may help you figure out how this
work:
"""

class Stub:
    def __len__(self):
        return 10
    def __getitem__(self, *args):
        print "getitem", args, map(type, args)
    def __getslice__(self, *args):
        print "getslice", args, map(type, args)

s = Stub()
print "*** single index:"
s[0]
print "*** slice:"
s[0:2]
print "*** ellipsis:"
s[...]
print "*** extended slice:"
s[0:2:2]
print "*** multidimensional slice:"
s[10, 10:20, 20:100:5, ...]

"""
Depending on how you specify the index or the slice, you'll
end up in either __getitem__ or __getslice__, with integers
or instances of the "slice" or "ellipsis" types.

slice instances have three attributes: start, stop, and step.

Hope this helps!
"""