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, 'Adress of A') Marks: 85.0 ('Student B', 9999999999, 'Adress of B') Marks: 79.8 ('Student C', 8888888888, 'Adress 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(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.
slice(1, 5, 2) corresponds to
slice(1, 4) corresponds to
Let’s rewrite our code.
('Student A', 9876543210, 'Adress of A') MArks: 85.0 ('Student B', 9999999999, 'Adress of B') MArks: 79.8 ('Student C', 8888888888, 'Adress of C') MArks: 67.8 387.6666666666667
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.