Reading Time: 1 minutes
Naming Slices in Python
The constructor of the builtin slice class creates a slice object, which can be used in places where a slice is normally employed. It is a better alternative to hardcoded slices, especially when they begin to create readability and maintenance issues.
>>> listOfNumbers = [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] |
>>> TWOtoFOUR = slice ( 2 , 5 ) # Slices include elements from starting index to ending index - 1. |
>>> TWOtoFOUR |
slice ( 2 , 5 , None ) # The step size is 0, hence the None. |
>>> listOfNumbers[TWOtoFOUR] |
[ 2 , 3 , 4 ] |
>>> listOfNumbers[ 2 : 5 ] |
[ 2 , 3 , 4 ] |
>>> listOfNumbers[TWOtoFOUR] = [ 12 , 13 , 14 ] |
>>> listOfNumbers |
[ 0 , 1 , 12 , 13 , 14 , 5 , 6 , 7 , 8 , 9 ] |
The slice objects provide three read-only attributes to access the indices individually. These are start, stop & step.
>>> twoToFourWithStepOne = slice ( 2 , 5 , 1 ) |
>>> twoToFourWithStepOne.start |
2 |
>>> twoToFourWithStepOne.stop |
5 |
>>> twoToFourWithStepOne.step |
1 |
In addition to these attributes, it also provides a method called indices(). The indices() method is used to map a slice onto a sequence of a specific size. It takes length of the sequence as input and returns a tuple(start, stop, step) in such a manner that out of bounds indices are clipped to fit within bounds.
>>> x = slice ( 2 , 25 , 3 ) |
>>> seq = 'Hi, my name is Ethan.' |
>>> x.indices( len (seq)) |
( 2 , 21 , 3 ) |