[Tutor] Thanks re: [::-1]

Alan Gauld alan.gauld at btinternet.com
Thu Jul 26 23:47:15 CEST 2007


"Charles Cuell" <cuell at snoopy.usask.ca> wrote

> The one odd thing about Python's slice notation is that the -1 means 
> to
> start from the end and work backwards.  My first inclination would 
> have
> been to assume that -1 means to start at i and go to j by steps 
> of -1
> (only nonempy if j < i).

I mentally resolve this by thinking of sequences as being circular.
Thus the -1 character is the last one - the one before the first.

But that doesn't work for the step size k, you just have to realise
that the minus sign there means work backwards and therefore
start from the second parameter. However...

>>> 'abcdefgh'[3:1:-1]
'dc'
>>> 'abcdefgh'[1:3:-1]
''
>>> 'abcdefgh'[::-1]
'hgfedcba'

It seems that if you do provide values for j,k the first must be 
bigger
than the second to work so Python is being slightly more intelligent
about the default values than I initially thought, but the docs do 
say:
----------------
If i or j are omitted or None, they become ``end'' values
(which end depends on the sign of k).
---------------

How interesting. And thank goodness for the >>> prompt.
- the ultimate arbiter and test...

Alan G.










More information about the Tutor mailing list