3.1.6.3 Operations on lists | slices

Slices - negative indices

Look at the snippet below:
myList[start:end]
To repeat:
  • start is the index of the first element included in the slice;
  • end is the index of the first element not included in the slice.

This is how negative indices work with the slice:
myList = [10, 8, 6, 4, 2] newList = myList[1:-1] print(newList)
The snippet's output is: [8, 6, 4].

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:
myList = [10, 8, 6, 4, 2] newList = myList[-1:1] print(newList)
The snippet's output is: [].


  • Console 

Comments

Popular Posts