python - What are the default values set to in a slice? -
i have had @ top answers on why-does-list-1-not-equal-listlenlist-1 , what-are-the-default-slice-indices-in-python-really learn default values set in slice. both of top answers refer following documentation:
given s[i:j:k],
if or j omitted or none, become “end” values (which end depends on sign of k). note, k cannot zero. if k none, treated 1.
suppose have following code:
s = "hello" forward_s = s[::1] print(forward_s) # => "hello" backward_s = s[::-1] print(backward_s) # => "olleh" i know if indices omitted python treats if value of none used in places. according documentation indices of i , j in [i:j:k] set "end" values depending on sign of k. positive k, i'm assuming i set 0 , j set length of string. values set negative k though?
for instance, following reverses string:
reversed_str = s[-1:-6:-1] so maybe default value i set -1 , j set -len(s) - 1 when k = -1?
the default values none, none, , none.
class sliceable(object): def __getitem__(self, slice): print(slice) sliceable()[::] >>> slice(none, none, none) this regardless of fact, slice() require stop argument. library documentation little bit less explicit on this, c api makes clear, 3 values maybe empty:
the
start,stop, ,stepparameters used values of slice object attributes of same names. of values maynull, in casenoneused corresponding attribute.
it's sliceable object make sense of default values. convention use first element, past last element, minimal stepping implemented builtin collections:
l = [1, 2, 3] l[slice(none, none, none]) >>> [1, 2, 3] s[none:none:none]) >>> [1, 2, 3] negative stepping cause default start , end values reversed semantically, i.e.:
s = 'abc' s[slice(none, none, -1)] >>> 'cba' s[::-1] >>> 'cba' note not mean simple value flip, default value of end typically "one past end of sequence, in whatever direction", since range() not inclusive end value, default values slice should include full sequence.
this documented here:
s[i:j:k]the slice of
sijstepkdefined sequence of items indexx = + n*ksuch0 <= n < (j-i)/k. in other words, indicesi, i+k, i+2*k, i+3*k, on, stopping whenjreached (but never includingj). whenkpositive,i,jreducedlen(s)if greater. whenknegative,i,jreducedlen(s) - 1if greater. ifiorjomitted or none, become “end” values (which end depends on sign ofk). note,kcannot zero. ifknone, treated1.
Comments
Post a Comment