question on slices

John Warney john at yahoo.com
Tue Mar 26 02:14:20 EST 2002


This makes sense and cleared it up.
Thanx

Rob



On Mon, 25 Mar 2002 18:00:29 -0500, Michael Chermside
<mcherm at destiny.com> wrote:

>>>>> numlist[1:2]
>> [1]
>> 
>> This last one doesnt make since to me since i am asking for a range
>> from 1-2.  Why in the world does it give me 1 when i am asking for 1-2
>> which would logically be:
>> 
>>>>> numlist[1:2]
>> [1, 2]
>> 
>> but it's not. it doesnt make since.  Just seems strange when i just
>> was in a C++ class and it would do the logical thing.
>> 
>
>Actually, this *IS* doing the "logical" thing, but only once you get 
>into certain Python mindsets.
>
>In Python, all ranges are "half-open". That means that the lower end 
>point IS included, but the upper end point is not. You've encountered 
>this pattern before in C++:
>
>      for( int i=0; i<MAX; i++ )
>
>In that code, i will actually be 0, but it will NOT actually be MAX... 
>it gets no higher than MAX-1. This is the "standard" way to loop through 
>a list of length MAX in C++, and in Python it is the "standard" way to 
>do EVERYTHING... loops:
>
>      for x in range(10)   # Goes 0, 1, 2, ... 8, 9
>
>slices:
>
>      mylist[:10]     # Gives [ mylist[0], mylist[1], ... mylist[9] ]
>
>and a few other places which don't occur to me immediately.
>
>So Python has the wonderful advantage of being consistant.
>
>You could now start a whole debate about whether "half-open" is the best 
>rule to use... "closed" is the other popular option. I think you'll find 
>that "half-open" is a good choice, because it allows things like this:
>
>      first = mylist[:47]
>      last  = mylist[47:]
>
>which splits mylist into two parts, and doesn't skip or repeat any 
>elements. But what I really want to do is brag about the consistance, 
>not re-open the "half-open" vs "closed" debate again.
>
>-- Michael Chermside
>
>PS: Whoah! how early were YOU to be able to grab "john at yahoo.com" ? !
>
>




More information about the Python-list mailing list