I recently read a code snippets about how to reverse a sequence
>> l = [1,2,3,4,5,6]
>> print l[::-1]
>> [6,5,4,3,2,1]
How to explain the first colon in bracket?
The colons with no values given means resort to default values. The default values for the start index when the step is negative is len(l)
, and the end index is -len(l)-1
. So, the reverse slicing can be written as
l[len(l):-len(l)-1:-1]
which is of the form.
l[start:end:step]
Removing the default values, we can use it in a shorter notation as l[::-1]
.
It might be useful to go through this question on Python's Slice Notation.
some_list[start:end:step]
When you ommit any of the slicing operands they take on default values. Default values for start, end and step: start - the beginning of an indexated iterable which is always of an index 0 when step is positive, end - the ending index of an indexated iterable which is always its length (following the same convention as range) when step is positive, step - the default step is always one.
When you're using a minus sign on step omitting other operands you're basically saying "return a reversed list".
EDIT: Funny, but
[1,2,3,4,5,6][5:-7:-1]
returns the same result as
[1,2,3,4,5,6][::-1]
in Python3. Can anyone comment on to why? That means that default values of start and end actually rest upon the step operand (more specifically its sign).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With