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.
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.
To understand how the slice method works, let’s take a look below:
slice(start,stop,step)
start: This is an optional parameter which indicates the index that the range should start from. If not given, the default value is set to None.
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 the start and stop values.
Given that, the first and third parameters are not given. The slice method can also be called, as shown below:
slice(stop)
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.
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.
slice_object = slice(1,6,3)array = ['H','E','L','L','O']print(array[slice_object]);
stop parameterslice_object = slice(3)array = ['H','E','L','L','O']print(array[slice_object]);
slice with range out of boundsslice_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.
slice with negative valuesThe 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]);
slice to index a tupleslice_object = slice(0,6,2)array = ('H','E','L','L','O')print(array[slice_object]);
slice in the print statementarray = ['H','E','L','L','O']print(array[slice(3)]);
Free Resources