[Tutor] is the the two style of writting the same?

Walter Prins wprins at gmail.com
Tue Aug 20 21:31:11 CEST 2013


Hi,

On 20 August 2013 10:20, sikonai sikonai <tanjyunda at gmail.com> wrote:

> >>> list=[1,2,3,4,5,6,7,8,9]
> >>> list[9:0:-2]
> [9, 7, 5, 3]
> >>> list[10:0:-2]
> [9, 7, 5, 3]
>
> I want to know whether they have some difference.
>

For the specific list you show, the 2 expressions yield the same result.
 However this does not mean that this is true of any list.  The reason the
2 expressions return the same result is because the starting index for the
slice operation is effectively capped at 9, due to the list containing only
9 elements, so hence any value above 9 in the first slice parameter is
essentially reset/capped to 9.  For longer lists of course this is not true
so the results are different.  Play around with some longer/other examples
to see this:

Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> l = [1,2,3,4,5,6,7,8,9,10,11]  #note the extra elements as compared to
your example
>>> l[9:0]
[]
>>> l[9:0:-2]
[10, 8, 6, 4, 2]
>>> l[10:0:-2]
[11, 9, 7, 5, 3]
>>> l[12:0:-2]
[11, 9, 7, 5, 3]
>>> l[20:0:-2]
[11, 9, 7, 5, 3]
>>>


Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130820/b71a2308/attachment.html>


More information about the Tutor mailing list