InterviewSolution
| 1. |
What is the use of slice object in Python? |
|
Answer» Python’s built-in function SLICE() returns Slice object. It can be used to extract slice from a sequence object list, tuple or string) or any other object that implements sequence protocol SUPPORTING _getitem__() and __len__() methods. The slice() function is in fact the constructor in slice class and accepts start, stop and step parameters similar to range object. The start and step parameters are optional. Their default value is 0 and 1 respectively. Following STATEMENT declares a slice object. >>> obj=slice(1,6,2)We use this object to extract a slice from a list of numbers as follows: >>> numbers=[7,56,45,21,11,90,76,55,77,10] >>> numbers[object] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list indices must be integers or slices, not type >>> numbers[obj] [56, 21, 90]You can see that elements starting from index 1 upto 5 with step 2 are sliced away from the original list. Slice can also receive negative index. >>> obj=slice(-1,3,-1) >>> numbers[obj] [10, 77, 55, 76, 90, 11] |
|