extended slicing and negative stop value problem

Chris Angelico rosuav at gmail.com
Sat Aug 20 14:29:42 EDT 2011


On Sat, Aug 20, 2011 at 7:20 PM, Max Moroz <maxmoroz at gmail.com> wrote:
> Would it be a good idea to change Python definition so that a[10, -1, -1]
> referred to the elements starting with position 10, going down to the
> beginning?

Well, first off I think it's a dangerous idea to change semantics of
something like that. I can see your use case, but I think that what
you want is covered by simply omitting the stop marker:

>>> a="qwertyuiopasdfghjklzxcvbnm"
>>> a[10:1:-1]
'apoiuytre'
>>> a[10:0:-1]
'apoiuytrew'
>>> a[10::-1]
'apoiuytrewq'

If you're using a variable for the stop value, you just need to set it
to an explicit None if it would fall negative:

>>> a[10:None:-1]
'apoiuytrewq'

Hope that helps!

ChrisA



More information about the Python-list mailing list