Saturday, 10 September 2016

Python list slice




Why the first output is including the first element (is seems to me like good behavior, because it starts with 0 index (that is that first element) and then increment with len(a)-1 (last element)).



Problem is that the second example (if it always starts with zero index and then increment) should be something like [1, 5, 4, 3, 2], or?



Output 1: [1, 5]



Output 2: [5, 4, 3, 2, 1]



a = [1, 2, 3, 4, 5]


print(a[::len(a)-1])

print(a[::-1])

Answer



The last parameter in a slice is the step value. It starts from 0, if the step is positive, -1 if the step is negative. Relevant piece of code from sliceobject.c,



defstart = *step < 0 ? length-1 : 0;



So, when you say



a[::-1]


and as the step is negative, it just starts from the last element. It keeps on incrementing the index by -1 and the generated list is returned. So, it basically reverses the list.



But, when you say




a[::len(a)-1]


the step value is 4. Since the step is positive, it starts from the first element, which is 1 and increments the index by 4 and picks the element at index 4 (initial index (0) + 4 = 4), which is 5. That is why [1, 5] is returned.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...