Online Tutorials & Training Materials | STechies.com
Register Login

slice() in Python

|| 0

slice() in Python
Stechies

Definition

Python slice() function creates a slice of elements from a group of elements. Python slice() function return slice object, which represents the set of indices specified by range(start, stop, step)

In other words, a slice object is used to specify the start and endpoint of slicing. 

Syntax

slice (start, stop, step). 

Parameter Value

Parameter Type Description
            

start (optional)

            
Integer    
  • Specify the position to start slicing    
  • Default value is 0
end (mandatory) Integer Specify the position to end slicing
step (optional) Integer             
  • Specify the step of slicing
  • Default value is 1

            

Return Value

Python slice() function returns slice object, which used to specify the sequence of slicing in the given indices.

Example of Python slice() List without step value

#Python program to illustrate the working of slicing function

#Using List (Without steps value)

my_List = [0,1,2,3,4,5,6,7,8,9]

#index   0,1,2,3,4,5,6,7,8,9
#index   -10,-9,-8,-7,-6,-5,-4,-3,-2,-1

slicedValueObject = slice(0,5)

print(my_List[slicedValueObject])

Output

[0, 1, 2, 3, 4]

Example 2: Python slice() List with step value

#Python program to illustrate the working of slicing function

#Using List (With steps value)

my_List = [0,1,2,3,4,5,6,7,8,9]

#index   0,1,2,3,4,5,6,7,8,9
#index   -10,-9,-8,-7,-6,-5,-4,-3,-2,-1

slicedValueObject = slice(0,5,2)

print(my_List[slicedValueObject])

OUTPUT:

[0, 2, 4] 

Example 3: Python slice() with String without step value

#Python program to illustrate the working of slicing function

#Using String (without step value)

my_string = "You are on stechies.com"

#index   0,1,2,3,4,5,6,7,8,9
#index   -10,-9,-8,-7,-6,-5,-4,-3,-2,-1

mySubString = slice(0,10);

print(my_string[mySubString])

OUTPUT:

You are on 

Example 4: Python slice() with String with step value

#Python program to illustrate the working of slicing function

#Using String with alternate approach (with step value)

my_string = "You are on stechies.com"

#index   0,1,2,3,4,5,6,7,8,9
#index   -10,-9,-8,-7,-6,-5,-4,-3,-2,-1

mySubString = slice(0,10,3);

print(my_string[mySubString])

OUTPUT:

Y en 

Example 4: Python slice() with String with negative index

#Python program to illustrate the working of slicing function

#Using String with alternate approach (with negative index)

my_string = "You are on stechies.com"

#index     0,1,2,3,4,5,6,7,8,9
#index     -10,-9,-8,-7,-6,-5,-4,-3,-2,-1

mySubString = slice(-15,-4);

print(my_string[mySubString])

OUTPUT

on stechies