How to retrieve parameters of a slice object in python ?

Published: February 23, 2021

Tags: Python;

DMCA.com Protection Status

Example of how to retrieve parameters of a slice object in python:

Create a simple slice object in python

Let's create a simple slice object in python:

start = 5
stop = 8
step = 1

s1 = slice(start, stop, step)

returns

slice(5, 8, 1)

Note to check if an object is a slice:

isinstance(s1, slice)

returns here

True

Get slice object index

To retrieve parameters from a slice object:

print(s1.start)
print(s1.stop)
print(s1.step)

returns

5
8
1

Print elements from a slice object

for i in range(s1.start,s1.stop,s1.step):
    print(i)

5
6
7

Create a list from a slice object

l1 = [i for i in range(s1.start,s1.stop,s1.step)]

print(l1)

returns

[5, 6, 7]

References