Python Built-in Function slice:

The slice() is a built-in function in Python that returns an object of type slice representing the set of indices specified by range(start, stop, step). Here, the start and step arguments default to None.

Slice objects have read-only data attributes start, stop, and step, which merely returns the argument values. This slice object can be used to slice a Python sequence such as a string, a tuple, a list, etc.

Method signature

The signature for the slice() function is as shown below. It has two different variants.

slice(stop)
slice(start, stop,step)

Method parameters and return type

  • This function takes starting index, stopping index and step as a parameter. Furthermore, the other variant takes only the stopping index as a parameter assuming starting value as 0 and the step of 1.
  • However, it returns an object of type slice.

Python Built-in Function slice Examples:

Example 1: We will take only the stopping parameter to slice on a String for this example.

#Initializing
st = 6
x = 'Python Programming'
#Using slice and Printing
o = slice(st)
print(x[o])

Output

Python

Example 2: In this case, we will demonstrate a slice function with a list of numbers. Here, we use only two parameters, a start and a stop.

#Initializing
sta = 3
sto=6
x=[100,200,300,400,500,600,700,800]

#Using slice and Printing
o = slice(sta,sto)
print(x[o])

Output

[400, 500, 600]

Example 3: Let us take a list containing numbers for this example. Thereafter, we will slice using all three parameters.

#Initializing
sta = 3
sto=6
step=2
x=[100,200,300,400,500,600,700,800]

#Using slice and Printing
o = slice(sta,sto,step)
print(x[o])

Output

[400, 600]

Conclusion

Hence, the slice() function returns a slice object, a subset of the object itself.

References

Happy Learning 🙂

Leave A Comment