Title: Equivalent syntax regarding List returns List objects with non-similar list elements.
Type: behavior Stage: resolved
Components: Versions: Python 3.6
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Akshay Deogaonkar, steven.daprano
Priority: normal Keywords:

Created on 2017-04-22 14:01 by Akshay Deogaonkar, last changed 2017-04-22 18:16 by steven.daprano. This issue is now closed.

Messages (2)
msg292120 - (view) Author: Akshay Deogaonkar (Akshay Deogaonkar) Date: 2017-04-22 14:01
lst = [0,1,2,3,4]
print(lst[0:3]) #returns [0,1,2]
print(lst[:3]) #returns [0,1,2]

#Above two syntax returns same lists.

print(lst[0:3:-1]) #returns []
print(lst[:3:-1]) #returns [4]

#Here is a bug; what expected was that the both syntax would have
returned the similar lists; however, they didn't!
msg292132 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2017-04-22 18:16
The behaviour is as documented and is not a bug. When you have a three-argument extended slice, the starting and stopping values depend on whether the stride (step) is positive or negative. Although that's buried in a footnote to the table.

The current behaviour is necessary so that the common case of both start and stop being blank is supported correctly for negative stride:

py> "abcde"[::-1]

So with a positive stride, your first example lst[0:3:-1] starts at index 0, ends at index 3, with step -1. That is an empty slice.

But your second example lst[:3:-1] starts at the end of the list, index len(lst), ends at 3, with step -1. That is equivalent to lst[5:3:-1] which is not the same as your first example.
Date User Action Args
2017-04-22 18:16:43steven.dapranosetstatus: open -> closed

nosy: + steven.daprano
messages: + msg292132

resolution: not a bug
stage: resolved
2017-04-22 14:01:58Akshay Deogaonkarcreate