Python slice() function

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

String slicing
GeeksforGe
se

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

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.