Tutorial Study Image

Python slice()

The built-in function slice() is used to slice a given object or a sequence. The sequence may be a string, bytes, tuple, list, or range. The function allows specifying where to start and where to end the splicing also with the step.


slice(start, stop, step) #where all parameters should be integers
 

slice() Parameters:

Takes three parameters. If the first and third parameter is emitted we can write the syntax as slice(stop).

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

slice() Return Value

This return slice object contains the set of indices from the specified range.

Input Return Value
 If parameters slice object

Examples of slice() method in Python

Example 1: How to 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)

Example 2:How to 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: How to 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 4: How to 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 5: How to use Indexing Syntax for Slicing


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