Python slice() function


The slice() function implements slicing objects, returns a sliced object. This is the same thing as an index, so the usage is the same as an index, nums[slice].

Related course: Complete Python Programming Course & Exercises

Syntax

class slice(stop)
class slice(start, stop[, step])

It has these parameters:

  • start -- starting position
  • stop -- end position
  • step -- spacing

Slice() with one parameter

Enter 1 parameter in slice() and the incoming one parameter defaults to the termination location

For example, enter parameter 4, the first 4 numbers are cut out for list a The code is as follows.

s=slice(4)
a=range(10)
list(a[s]) #use slice(4) for a and convert to list

The final return is

[0, 1, 2, 3]

Slice() with two parameters

The two incoming parameters mean the starting position and the ending position respectively.

For example, enter parameters 4 and 9, and for list a cut out is 4 to 8 (left closed right open)

The code is as follows.

s=slice(4,9)
a=range(10)
list(a[s])

The last to return is

[4, 5, 6, 7, 8]

slice() with three parameters

The three incoming parameters are the starting position, the ending position and the step length.

For example, enter parameters 4, 9 and 2, and cut out the list a to take 4 to 8 in two intervals (left closed and right open)

The code is as follows.

s=slice(4,9,2)
a=range(10)
list(a[s])

Returns

[4, 6, 8]

slice() without parameters

So that's slicing all the data.

s=slice(None)
a=range(10)
list(a[s])

The final result is

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

slice() with variables

You can use this as alternative to the [] slicing.

>>> s = "Programming"
>>> res = s[slice(0,5)]
>>> res
'Progr'
>>> 
>>> s = ["Wendy","Tina", "Gina", "Fiona" ]
>>> s[slice(0,2)]
['Wendy', 'Tina']
>>>