Python slice() Function
Returns a slice object. A slice object is an object that is used to slice (cut up) any indexable collection (string, tuple, list, range, or bytes).
Syntax
Python
Copy Code
slice(stop) slice(start, stop, step)
Parameters
Parameter | Description |
---|---|
start |
Required if step is provided. The index at which to start the slice. The default is 0. |
stop |
Required. The indes at which to stop slicing |
step |
Required if start is provided. The number of items to step in each iteration. For instance, a step of 2 means every second index will be included in the slice. The default is 1. |
Example
Python
Copy Code
a = ("a", "b", "c", "d", "e", "f", "g", "h") x = slice(2) print(x) print(a[x])
Output
slice(None, 2, None) ('a', 'b')
Notes
The slice()
function can be specified with start, end, and step parameters.
In the following example, the slice()
function starts at index 2, ends at index
8, and steps by 3.
Example
Python
Copy Code
a = ("a", "b", "c", "d", "e", "f", "g", "h") x = slice(2, 8, 3) print(x) print(a[x])
Output
slice(2, 8, 3) ('c', 'f')