The slice()
function returns a slice object that is used to slice any sequence (string, tuple, list, range, or bytes).
Example
text = 'Python Programing'
# get slice object to slice Python
sliced_text = slice(6)
print(text[sliced_text])
# Output: Python
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
# contains indices (0, 1, 2)
result1 = slice(3)
print(result1)
# contains indices (1, 3)
result2 = slice(1, 5, 2)
print(slice(1, 5, 2))
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
# Program to get a substring from the given string
py_string = 'Python'
# stop = 3
# contains 0, 1 and 2 indices
slice_object = slice(3)
print(py_string[slice_object]) # Pyt
# start = 1, stop = 6, step = 2
# contains 1, 3 and 5 indices
slice_object = slice(1, 6, 2)
print(py_string[slice_object]) # yhn
Output
Pyt yhn
Example 3: Get substring using negative index
py_string = 'Python'
# start = -1, stop = -4, step = -1
# contains indices -1, -2 and -3
slice_object = slice(-1, -4, -1)
print(py_string[slice_object]) # noh
Output
noh
Example 4: Get sublist and sub-tuple
py_list = ['P', 'y', 't', 'h', 'o', 'n']
py_tuple = ('P', 'y', 't', 'h', 'o', 'n')
# contains indices 0, 1 and 2
slice_object = slice(3)
print(py_list[slice_object]) # ['P', 'y', 't']
# contains indices 1 and 3
slice_object = slice(1, 5, 2)
print(py_tuple[slice_object]) # ('y', 'h')
Output
['P', 'y', 't'] ('y', 'h')
Example 5: Get sublist and sub-tuple using negative index
py_list = ['P', 'y', 't', 'h', 'o', 'n']
py_tuple = ('P', 'y', 't', 'h', 'o', 'n')
# contains indices -1, -2 and -3
slice_object = slice(-1, -4, -1)
print(py_list[slice_object]) # ['n', 'o', 'h']
# contains indices -1 and -3
slice_object = slice(-1, -5, -2)
print(py_tuple[slice_object]) # ('n', 'h')
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,
py_string = 'Python'
# contains indices 0, 1 and 2
print(py_string[0:3]) # Pyt
# contains indices 1 and 3
print(py_string[1:5:2]) # yh
Output
Pyt yh