[Python-ideas] [Python-Dev] Inclusive Range

Terry Reedy tjreedy at udel.edu
Fri Oct 8 17:05:26 EDT 2010


On 10/8/2010 4:21 AM, Antoon Pardon wrote:
> On Wed, Oct 06, 2010 at 05:28:13PM -0400, Terry Reedy wrote:

>> Strings and tuples are not natural numbers, but do have least
>> members ('' and ()), so the bottom end had better be closed.
>
> Why?

Because otherwise one can never include the least member in a slice.

 > The fact that we have a bottom element in the item space,
> doesn't imply that the sequence I need is easiest defined by
> using an inclusive lower limit. What if I wanted all none-empty
> strings/tuples keys in the tree?

Use 'a' as the lower bound, it being the string that follows ''.

But you really seem to be saying is "What if I sometimes want the end 
points included and sometimes do not?"  Slice syntax by itself cannot 
handle all four cases, only one, one was chosen and that was closed-open.

If you want flexibility, consider the following:

class my_list(list):
     def __getitem__(self, key, include_start=True, include_stop=False):
         if (isinstance(key,tuple) and len(key)==2 and 
isinstance(key[0], slice)
           and isinstance(key[1],tuple) and len(key[1])==2):
             key, (include_start, include_stop) = key
             start,stop,stride = key.indices(len(self))
             if include_start == False:
                 start += 1
             if include_stop == True:
                 stop += 1
             key = slice(start,stop,stride)
             print(key)
         return list.__getitem__(self, key)

ll = my_list(range(10))

print('standard:', ll[2], ll[1:3], ll[1:3,(True,False)])
print('delete start:', ll[1:3,(False,False)])
print('shift:', ll[1:3,(False,True)])
print('extend stop:', ll[1:3,(True,True)])

 >>>
slice(1, 3, 1)
standard: 2 [1, 2] [1, 2]
slice(2, 3, 1)
delete start: [2]
slice(2, 4, 1)
shift: [2, 3]
slice(1, 4, 1)
extend stop: [1, 2, 3]
 >>>

Modify to taste ;-)

-- 
Terry Jan Reedy




More information about the Python-list mailing list