Python slice() With Examples

Python slice() function returns a slice object representing the set of indices specified by range(start, stop, step).

Python slice()

Python slice function syntax is:

Note that slice function returns slice object. We can pass this object as a set of indices with sequences such as string, list, tuple etc.

Python slice function allows us to create a stepwise sub-sequence easily without doing complete iteration on the existing sequence.

slice() function arguments

  • start: specifies the start of the index value. It’s optional and defaults to None.
  • stop: specifies the end of the index value. This is a mandatory parameter.
  • step: specifies the steps to take from start to stop index. It’s an optional parameter and defaults to None.

Python slice object has read-only data attributes – start, stop and step – which return the argument values (or default value).

Let’s see how to create slice objects.

Output:

Python slice object has no use on its own, it’s useful when used in conjunction with sequences to create a sub-sequence.

Python slice string

Let’s see how to use slice function with string. We will pass slice object just like a normal index to get the substring value from a string.

Output: bd

Note that if the slice indexes are more than the length of the sequence, no exception is raised and data is returned till the maximum available index.

We can also pass negative values for slice() function. In that case, the iteration will be performed backward i.e. from end to start.

Output: ed

Python slice list/array

Let’s look at an example of using slice() function with list or array.

Output: [1, 2, 3]

Python slice tuple

We can use slicing with tuple too because it’s a sequence.

Output: [1, 2]

Python slice extended indexing syntax

Since slicing is very popular in numerical python, there is a shorthand way to create a slice object.

Let’s see some examples of slicing using the shorthand approach.

Output:

The output is self-explanatory and important details are already mentioned in the comments.

Summary

Python slice() is a very useful function. We can create sub-sequence based on steps, start and end indexes easily without doing complete iteration.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: