Python slice() Function in Linux

The slice() function in Python prints a slice object, which can be a string, byte, tuple, list, and range. With this function, you can specify the start and endpoints and even the step to cut.

Basically, this function's job is to take the elements in an array of the original list and create a new list.

Here at LinuxAPT, as part of our Server Management Services, we regularly help our Customers to perform related Python function queries.

In this context, we shall look into how to use the slice() function in Python.

What is the slice() Function in Python ?

The slice() function prints out a slice object.

Here, You can specify the start and endpoints and even the step to cut.

It's syntax is given below:

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).

Examples of using slice() Function in Python 

1. Let's take a quick look at the below slice() function:

a = ("b", "c", "d", "e", "f", "g", "h")
x = slice(3)

It's Output would be:

(‘b’, ‘c’, ‘d’)

2. slice() function has a start and endpoint:

a = ("b", "c", "d", "e", "f", "g", "h")
x = slice(3,6)

The Output will be:

(‘e’, ‘f’, ‘g’)

3. slice() function has a start, endpoint and step is 2

a = ("b", "c", "d", "e", "f", "g", "h")
x = slice(0,6,2)

It's Output will be:

(‘b’, ‘d’, ‘f’)

4. 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

The output will be:


[Need help in fixing Python function issues ? We can help you. ]

This article covers how to use the slice() function in Python. In fact, the slice() function returns a slice object that is used to slice any sequence (string, tuple, list, range, or bytes).

Example of slice() function in Python:

text = 'Python Programing'
# get slice object to slice Python
sliced_text = slice(6)

The will be Output: 


Related Posts