sequence - Indexing lists in python, for a range of values -


to knowledge, indexing -1 bring last item in list e.g.

list = 'abcdefg' list[-1]  'g' 

but when asking sequence list, -1 gives second last term in list,

list[3:-1]  'def' 

why? have expected, , defg

it because stop (second) argument of slice notation exclusive, not inclusive. so, [3:-1] telling python index 3 to, not including, index -1.

to want, use [3:]:

>>> list = 'abcdefg' >>> list[3:] 'defg' >>> >>> list[3:len(list)]  # equivalent doing:  list[3:] 'defg' >>> 

also, note future: considered bad practice use list variable name. doing overshadows built-in.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -