slice() Builtin Function

Python slice()

Python slice() builtin function is used to create a slice object. The slice object can be used to extract a slice of an iterable like list, tuple, string, etc.

In this tutorial, you will learn the syntax of slice() function, and then its usage with the help of example programs.

Syntax

The syntax of slice() function is

slice(stop)
slice(start, stop, step=1)

where

ParameterDescription
startStarting index of the slice.
stopEnding index of the slice.
step[Optional] Step value which defines the difference between adjacent indices in the slice object.

Examples

1. Slice a list

In the following program, we take a list object in variable x, and slice it in the index range [2, 5) using using slice() function.

Python Program

x = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

x_slice = slice(2, 7)

output = x[x_slice]
print(output)
Run Code Copy

Output

[6, 8, 10, 12, 14]

2. Slice a string

Now, we take a string, and find the substring of this string, using slice() function.

Python Program

x = 'abcdefghijklmnopq'

x_slice = slice(2, 7)

output = x[x_slice]
print(output)
Run Code Copy

Output

cdefg

Summary

In this tutorial of Python Examples, we learned the syntax of slice() builtin function, and how to use slice() function to get the slice of an iterable, with examples.

Related Tutorials

Code copied to clipboard successfully 👍