Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python slice() function

  • Difficulty Level : Basic
  • Last Updated : 30 Sep, 2021

Python slice() function returns a slice object. 

A sequence of objects of any type(string, bytes, tuple, list or range) or the object which implements __getitem__() and __len__() method then this object can be sliced using slice() method.
 

Syntax: 

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

Parameters: 

  • start: Starting index where the slicing of object starts.
  • stop: Ending index where the slicing of object stops.
  • step: It is an optional argument that determines the increment between each index for slicing.

Return Type: Returns a sliced object containing elements in the given range only. 
 

Note: If only one parameter is passed then start and step is considered to be None.

Example 1: Python slice string

Python3




# Python program to demonstrate
# slice() operator
 
# String slicing
String = 'GeeksforGeeks'
s1 = slice(3)
s2 = slice(1, 5, 2)
 
print("String slicing")
print(String[s1])
print(String[s2])

Output:

String slicing
Gee
ek

Example 2: Python slice list or Python slice array

Python3




# Python program to demonstrate
# slice() operator
 
# List slicing
L = [1, 2, 3, 4, 5]
s1 = slice(3)
s2 = slice(1, 5, 2)
print("List slicing")
print(L[s1])
print(L[s2])

Output:

List slicing
[1, 2, 3]
[2, 4]

Example 3: Python slice tuple

Python3




# Python program to demonstrate
# slice() operator
 
# Tuple slicing
T = (1, 2, 3, 4, 5)
s1 = slice(3)
s2 = slice(1, 5, 2)
print("\nTuple slicing")
print(T[s1])
print(T[s2])

Output:

Tuple slicing
(1, 2, 3)
(2, 4)

Negative indexing

In Python, negative sequence indexes represent positions from the end of the array. slice() function can also have negative values. In that case, the iteration will be performed backward i.e from end to start.

Python3




# Python program to demonstrate
# slice() operator
 
# String slicing
String = 'GeeksforGeeks'
s1 = slice(-3)
s2 = slice(-1, -5, -2)
print("String slicing")
print(String[s1])
print(String[s2])
 
# List slicing
L = [1, 2, 3, 4, 5]
s1 = slice(-3)
s2 = slice(-1, -5, -2)
print("\nList slicing")
print(L[s1])
print(L[s2])
 
# Tuple slicing
T = (1, 2, 3, 4, 5)
s1 = slice(-3)
s2 = slice(-1, -5, -2)
print("\nTuple slicing")
print(T[s1])
print(T[s2])

Output: 

String slicing
GeeksforGe
se

List slicing
[1, 2]
[5, 3]

Tuple slicing
(1, 2)
(5, 3)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!