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.
Syntax
The syntax of slice()
function is
slice(stop)
slice(start, stop, step=1)
where
start
is the starting index.stop
is the ending index.step
[optional] is the 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 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 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.