Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the slice() function do in Python?

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.

like image 660
ForceBru Avatar asked Jul 19 '15 13:07

ForceBru


1 Answers

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.

like image 120
enrico.bacis Avatar answered Sep 22 '22 12:09

enrico.bacis