36

First of all, I'd like to clarify the question: it's about the slice() function, not slices of lists or strings like a[5:4:3].

The docs mention that this function is used in NumPy and give no examples of usage (it's said how to use it but it's not said when to use it). Moreover, I've never seen this function used in any Python program.

When should one use the slice() function when programming in plain Python (without NumPy or SciPy)? Any examples will be appreciated.

1
  • It is actually a class, which returns a slice object. See my full answer below.
    – RufusVS
    Oct 5, 2018 at 15:20

4 Answers 4

35

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.

5
  • Okay, I got it. So, there are no more cases where one could use slice()?
    – ForceBru
    Jul 19, 2015 at 14:04
  • 9
    @ForceBru: As usually in programming, the uses are only bounded by your creativity ;) Jul 19, 2015 at 14:05
  • 3
    It's only rarely necessary to create a slice object yourself. The most common situation where you'll use a slice object is when you're writing your own sequence type and want to support slicing of the items it contains. Whenever some other code uses slice notation on your an instance of your class Python will call your __getitem__ method with a slice object. (Older versions of Python used a __getslice__ method instead of this approach, but that has been deprecated since 2.6, and support for it is gone completely in Python 3.)
    – Blckknght
    Jul 19, 2015 at 16:07
  • @Blckknght Yeah, good explanation. Didn't saw it in time, so I added an answer. At least it contains an example, so I am not completely copying you. But why on earth you suggest only usage to be with sequence types? You may use it for whatever you want. Doesn't even need to do any slicing at all.
    – Dalen
    Jul 19, 2015 at 19:40
  • I think you should have given an example of what you stated (storing a slice object to be used later). I added an answer which I believe clarifies it.
    – RufusVS
    Oct 5, 2018 at 15:19
11

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.

1
  • 2
    Edited my answer to avoid calling slice a function.
    – RufusVS
    Oct 9, 2018 at 16:57
11

(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 in each 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.

4

From your question I believe you are looking for an example. So here is what I have when I try to slice a list from range(1, 20) with a step of 3

>>> x = range(1, 20)

>>> x[1:20:3]
[2, 5, 8, 11, 14, 17]

>>> x[slice(1, 20, 3)]
[2, 5, 8, 11, 14, 17]
1
  • @JonClements fixed answer with the slice function
    – user378704
    Jul 19, 2015 at 14:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.