Python Function

slice() in Python

slice() in Python

Introduction

To extract a slice of the elements from the collection of elements, use the slice() method in Python. Python comes with two redundant slice routines. While the second method needs three arguments and returns a slice object, the first function only requires a single argument. You can retrieve a part of the collection using this slice object. Slice can be applied here, for instance, if we want to get the first two elements from a list of 10 components. The function's signature is provided below.

Syntax

slice (stop
slice (start, stop[, step])  

Parameters

start: Slicing index at where to begin.

stop: Slice's final index

Step: The number of steps needed to jump.

Return

A slice object is the result.

Examples

To comprehend the functioning of the slice() function, let's look at some samples:

Example 1:

# Python slice() function example 
# Calling function 
result = slice(5) # returns slice object 
result2 = slice(0,5,3) # returns slice object 
# Displaying result 
print(result) 
print(result2)  

Output:

slice(None, 5, None)
slice(0, 5, 3)

write your code here: Coding Playground

Example 2:

# Python slice() function example 
# Calling function 
str1 = "BoardInfinity" 
slic = slice(0,10,3) # returns slice object 
slic2 = slice(-1,0,-3) # returns slice object 
# We can use this slice object to get elements 
str2 = str1[slic] 
str3 = str1[slic2] # returns elements in reverse order 
# Displaying result 
print(str2) 
print(str3)  

Output:

Brnn
ynnr

Example 3:

# Python slice() function example 
# Calling function 
tup = (45,68,955,1214,41,558,636,66) 
slic = slice(0,10,3) # returns slice object 
slic2 = slice(-1,0,-3) # returns slice object 
# We can use this slice object to get elements 
str2 = tup[slic] 
str3 = tup[slic2] # returns elements in reverse order 
# Displaying result 
print(str2) 
print(str3)  

Output:

(45, 1214, 636)
(66, 41, 68)

Example 4:

# Python slice() function example 
# Calling function 
tup = (45,68,955,1214,41,558,636,66) 
slic = slice(0,10,3) # returns slice object 
slic2 = tup[0:10:3] # fetch the same elements 
# We can use this slice object to get elements 
str2 = tup[slic] 
# Displaying result 
print(str2) 
print(slic2)  

Output:

(45, 1214, 636)
(45, 1214, 636)

write your code here: Coding Playground