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, , step parameters used values of slice object attributes of same names. of values may null, in case none used 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 s i j step k defined sequence of items index x = + n*k such 0 <= n < (j-i)/k. in other words, indices i, i+k, i+2*k, i+3*k , on, stopping when j reached (but never including j). when k positive, i , j reduced len(s) if greater. when k negative, i , j reduced len(s) - 1 if greater. if i or j omitted or none, become “end” values (which end depends on sign of k). note, k cannot zero. if k none, treated 1.


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -