What does the slice() function do in Python? What does the slice() function do in Python? python-3.x python-3.x

What does the slice() function do in Python?


a[x:y:z] gives the same result as a[slice(x, y, z)]. One of the advantages of a slice object is that it can be stored and retrieved later as a single object instead of storing x, y and z.

It is often used to let the user define their own slice that can later be applied on data, without the need of dealing with many different cases.


(Using function semantics) Calling the slice class instantiates a slice object (start,stop,step), which you can use as a slice specifier later in your program:

>>> myname='Rufus'>>> myname[::-1] # reversing idiom'sufuR'>>> reversing_slice=slice(None,None,-1) # reversing idiom as slice object>>> myname[reversing_slice]'sufuR'>>> odds=slice(0,None,2) # another example>>> myname[odds]'Rfs'

If you had a slice you often used, this is preferable to using constants in multiple program areas, and save the pain of keeping 2 or 3 references that had to be typed ineach time.

Of course, it does make it look like an index, but after using Python a while, you learn that everything is not what it looks like at first glance, so I recommend naming your variables better (as I did with reversing_slice, versus odds which isn't so clear.


No, it's not all!

As objects are already mentioned, first you have to know is that slice is a class, not a function returning an object.

Second use of the slice() instance is for passing arguments to getitem() and getslice() methods when you're making your own object that behaves like a string, list, and other objects supporting slicing.

When you do:

print "blahblah"[3:5]

That automatically translates to:

print "blahblah".__getitem__(slice(3, 5, None))

So when you program your own indexing and slicing object:

class example:    def __getitem__ (self, item):        if isinstance(item, slice):            print "You are slicing me!"            print "From", item.start, "to", item.stop, "with step", item.step            return self        if isinstance(item, tuple):            print "You are multi-slicing me!"            for x, y in enumerate(item):                print "Slice #", x                self[y]            return self        print "You are indexing me!\nIndex:", repr(item)        return self

Try it:

>>> example()[9:20]>>> example()[2:3,9:19:2]>>> example()[50]>>> example()["String index i.e. the key!"]>>> # You may wish to create an object that can be sliced with strings:>>> example()["start of slice":"end of slice"]

Older Python versions supported the method getslice() that would be used instead of getitem(). It is a good practice to check in the getitem() whether we got a slice, and if we did, redirect it to getslice() method. This way you will have complete backward compatibility.

This is how numpy uses slice() object for matrix manipulations, and it is obvious that it is constantly used everywhere indirectly.