Python slice() function
Python slice() function returns a slice object.
Python3
String = 'Hello World' slice_obj = slice ( 5 , 11 ) print (String[slice_obj]) |
Output:
World
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.
Python slice() Function Syntax:
Syntax: 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
# 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
# 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
# Tuple slicing T = ( 1 , 2 , 3 , 4 , 5 ) s1 = slice ( 3 ) s2 = slice ( 1 , 5 , 2 ) print ( "Tuple 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.
Example 4: Demonstrating negative index in slicing for different Python data-types.
Python3
# list -ve index slicing l = [ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' ] slice_obj = slice ( - 2 , - 6 , - 1 ) print ( "list slicing:" , l[slice_obj]) # string -ve index slicing s = "geeks" slice_obj = slice ( - 1 ) print ( "string slicing:" , s[slice_obj]) # tuple -ve index slicing t = ( 1 , 3 , 5 , 7 , 9 ) slice_obj = slice ( - 1 , - 3 , - 1 ) print ( "tuple slicing:" , t[slice_obj]) |
Output:
list slicing: ['e', 'd', 'c', 'b'] string slicing: geek tuple slicing: (9, 7)