Can someone explain why a[:5:-1] != a[:5][::-1]?
>>> a = range(10)
>>> a[:5][::-1]
[4, 3, 2, 1, 0]
>>> a[:5:-1]
[9, 8, 7, 6]
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The general syntax of slicings is
You can omit any of the three values
start,stop, orstep. If you omitstep, it always defaults to1. The default values ofstartandstop, by contrast, depend on the sign ofstep: ifstepis positive,startdefaults to0andstoptolen(a). Ifstepis negative,startdefaults tolen(a) - 1andstopto “beginning of the list”.So
a[:5:-1]is the same asa[9:5:-1]here,while
a[:5][::-1]is the same asa[0:5][4::-1].(Note that it’s impossible to give the default value for
stopexplicitly ifstepis negative. The stop value is non-inclusive, so0would be different from “beginning of the list”. UsingNonewould be equivalent to giving no value at all.)