Skip to content
Related Articles

Related Articles

Improve Article
Python slice() function
  • Last Updated : 11 Dec, 2019

A sequence of object 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




# 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
Gee
ek

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

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.

Example:




# 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)

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :