6

I am new to python and one of the things every newbie do come across is the slice operator. I have a list:

li=[1,2,3,4,5,6,7]

As per my understanding calling li[:-1] is same as calling li[0:-1] and it is but when using it with a negative steps things do not work exactly as I thought they would. So getting to my question why the result of

print(li[:-3:-2]) # is 7

but the result of

print(li[0:-3:-2]) # is []

Looking forward to some explanation of how the negative step is being treated in this scenario.

Tayyab
  • 1,207
  • 8
  • 29
  • I have no idea what the mechanics of this are - but if you need a workaround, doing `li[:-3][::-2]` instead of `li[:-3:-2]` produces the (expected) `[4, 2]`. – Green Cloak Guy Nov 25 '18 at 05:56
  • 4
    @GreenCloakGuy I am more interested in finding a proper explanation for this rather than a workaround :) – Tayyab Nov 25 '18 at 05:58

2 Answers2

7

The key is that missing (or None) start value is not always automatically set to 0. Please read the note 5 in sequence operations for s[i:j:k]

If i or j are omitted or None, they become β€œend” values (which end depends on the sign of k)

To simplify the situation, consider negative step -1 instead of -2. Step -1 is often used to reverse a list.

>>> print(li[None:-3:-1])
[7, 6]
>>> print(li[0:-3:-1])
[]

The first example shows, what are the real "end values" for the slice.

VPfB
  • 14,927
  • 6
  • 41
  • 75
2

So, your list is li=[1,2,3,4,5,6,7]

First, understand what exactly happens in slicing.

Slicing can't be done in backward direction without using step.

Take an example, we wan't to print [7, 6, 5, 4, 3, 2], we can't do this using li[-1:0]. because, slicing can't go backward as stated (we can't go backwards from index -1 to 0), and will return empty list [].(We have to do this using li[-1:0:-1])

So what happens here is:

you have a list li[x:y], using a negative step will swap the indexes as li[y:x].(Once swapping of indexes is done, you should consider it as a positive step) and then print out your output w.r.t. your provided step(only the magnitude).

Now, all that I mentioned above might seem useless, but it would help you understand next part.

So, coming to your question, when you write li[0:-3:-2], first,indexes are swapped. So, it is same as li[-3:0:2]. and as I have stated above, we can't go backwards (index -3 to 0) without using a negative step, so it returns the empty list.

but, when you give input as li[:-3:-2], It swaps the indexes and becomes li[-3::2] and we now easily know what will be the output ([7]).

So, don't consider the blank space in [:-3:-2] as 0 but as left end.(for better understanding)

Hope this helped.

Sandesh34
  • 279
  • 1
  • 2
  • 14