Use of slice() in Python
Sometimes the code becomes an unreadable mess of hardcoded slice indices. Consider the following code which stores the details of students(Name, Phone Number, Address, Marks in 5 subjects) in list, displays them one by one and finally displays the average total marks.
('Student A', 9876543210, 'Address of A') Marks: 85.0 ('Student B', 9999999999, 'Address of B') Marks: 79.8 ('Student C', 8888888888, 'Address of C') Marks: 67.8 387.6666666666667
The above code does its work but a problem that might occur with this code is that if in future we decide to add an entry “Roll no” at index 1. Then the whole code will need to be changed. Also, this code is not so good at readability either. This is just a small example. In large projects we write thousands of lines of codes. Therefore, it becomes our duty to write readable and maintainable code.
The same code can be made readable and maintainable to an extent by naming the slices using the slice() constructor.
- slice(start, stop, step)
start: Starting index where the slicing of object starts.
stop: Ending index where the slicing of object stops.
step: It is an optional argument that determines the increment between each index for slicing.
Return Type: Returns a sliced object containing elements in the given range only.
Note: slice(1, 5, 2) corresponds to a[1:5:2] and slice(1, 4) corresponds to a[1:4].
Let’s rewrite our code.
('Student A', 9876543210, 'Address of A') MArks: 85.0 ('Student B', 9999999999, 'Address of B') MArks: 79.8 ('Student C', 8888888888, 'Address of C') MArks: 67.8 387.6666666666667
Please Login to comment...