Python slice()

The slice() function returns a slice object that is used to slice any sequence (string, tuple, list, range, or bytes).

Example


slice() Syntax

The syntax of slice() is:

slice(start, stop, step)

slice() Parameters

slice() can take three parameters:

  • start (optional) - Starting integer where the slicing of the object starts. Default to None if not provided.
  • stop - Integer until which the slicing takes place. The slicing stops at index stop -1 (last element).
  • step (optional) - Integer value which determines the increment between each index for slicing. Defaults to None if not provided.

slice() Return Value

slice() returns a slice object.

Note: We can use slice with any object which supports sequence protocol (implements __getitem__() and __len()__ method).


Example 1: Create a slice object for slicing

Output

slice(None, 3, None)
slice(1, 5, 2)

Here, result1 and result2 are slice objects.

Now we know about slice objects, let's see how we can get substring, sub-list, sub-tuple, etc. from slice objects.


Example 2: Get substring using slice object

Output

Pyt
yhn

Example 3: Get substring using negative index

Output

noh

Example 4: Get sublist and sub-tuple

Output

['P', 'y', 't']
('y', 'h')

Example 5: Get sublist and sub-tuple using negative index

Output

['n', 'o', 'h']
('n', 'h')

Example 6: Using Indexing Syntax for Slicing

The slice object can be substituted with the indexing syntax in Python.

You can alternately use the following syntax for slicing:

obj[start:stop:step]

For example,

Output

Pyt
yh

Video: Slicing of Lists, Strings etc.