Wednesday, July 1, 2020

Slices with Negative Indices


Consider the below programs.






Output is


If the “start” specifies an element lying further than the one described by the "end" (from the list's beginning point of view), the slice will be empty.








Output is





If we omit the “start” in the slice, it is assumed that we want to get a slice beginning at the element with index “0”.


The slice of this form:


myList [ : end]
is equivalent to myList [ 0 : end]



Look at the code below.




Output is





If we omit the “end” in our slice, it is assumed that we want the slice to end at the element with the index “len (myList)”.

The slice of this form is myList [start : ] equivalent to myList [start : len (myList) ]

Consider the following snippet.




Output is






By omitting both “start” and “end” makes a copy of the whole list.








Output is



“del” instruction is able to delete more than just a list’s element at once, it can delete slices too.




In this case, the slice doesn’t produce any new list. So the output is







Deleting all the elements at once is possible.








Output is



Here the “del” instruction will delete the list itself, not its content.


The “print ( )” function invocation from the last line of the code will then cause a runtime error.








No comments:

Post a Comment