I have had a look at the top answers on why-does-list-1-not-equal-listlenlist-1 and what-are-the-default-slice-indices-in-python-really to learn about what the default values are set to in a slice. Both of the top answers refer to the following documentation:
Given s[i:j:k]
,
If i or j are omitted or None, they become “end” values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1.
Suppose I have the following code:
s = "hello"
forward_s = s[::1]
print(forward_s) # => "hello"
backward_s = s[::-1]
print(backward_s) # => "olleh"
I know that if the indices are omitted then Python treats that as if the value of None
was used in those places. According to the documentation the indices of i
and j
in [i:j:k]
are set to "end" values depending on the sign of k
. For a positive k
, I'm assuming i
is set to 0
and j
is set to the length of the string. What are the values set for a negative k
though?
For instance, the following also reverses the string:
reversed_str = s[-1:-6:-1]
So maybe the default value for i
is set to -1
and j
is set to -len(s) - 1
when k = -1
?