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
# 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)
Recommended Posts:
- Use of slice() in Python
- Python - Slice from Last Occurrence of K
- Python - Get sum of last K list items using slice
- Python | Pandas Series.str.slice()
- Python | Slice String from Tuple ranges
- Python | Incremental slice partition in list
- Python - Call function from another function
- Python | int() function
- Python | dir() function
- Python map() function
- ord() function in Python
- Python | oct() function
- Python | How to get function name ?
- Python tell() function
- sum() function in Python
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.

