How to use the slice() method in Python
Just like when you slice fruit to get particular pieces of it, you can slice an array, a list, or any structure that follows a sequence style in Python to separate out specific elements from it.
How does slice work in Python?
The slice method in Python returns a slice object. This object contains a list of indices specified by a range. This slice object can be used to index relevant elements from the given array, list, or even from a tuple.
Syntax
To understand how the slice method works, let’s take a look below:
slice(start,stop,step)
Parameters
-
start: This is an optional parameter which indicates the index that the range should start from. If not given, the default value is set toNone. -
stop: This is a required argument; it specifies the index at which the range of indices stops. -
step: This is an optional parameter which defines the increment between thestartandstopvalues.
Given that, the first and third parameters are not given. The slice method can also be called, as shown below:
slice(stop)
Return Value
The method returns a slice object. This object contains the set of indices that are obtained from the given range.
The illustration below shows how slice works on an array
In the illustration above, the slice object is simply used to index the array.
Code
Now, let’s look at some examples of how to use the slice() method to index arrays and tuples, and how both implementations of the method can be used.
1. Slicing an array
slice_object = slice(1,6,3)array = ['H','E','L','L','O']print(array[slice_object]);
2. Slicing an array with only the stop parameter
slice_object = slice(3)array = ['H','E','L','L','O']print(array[slice_object]);
3. Using slice with range out of bounds
slice_object = slice(3,6)array = ['H','E','L','L','O']print(array[slice_object]);
Note: As shown in the example above, if the value of
stopis out of bounds, and greater than the length of the array, it will simply proceed till the highest possible index.
4. Using slice with negative values
The negative index is taken as the last index of the array; hence, the array is indexed in reverse order.
slice_object = slice(-5,-1,2)array = ['H','E','L','L','O']print(array[slice_object]);
5. Using slice to index a tuple
slice_object = slice(0,6,2)array = ('H','E','L','L','O')print(array[slice_object]);
6. Using slice in the print statement
array = ['H','E','L','L','O']print(array[slice(3)]);
Free Resources