Why Python does *SLICING* the way it does??
Antoon Pardon
apardon at forel.vub.ac.be
Thu Apr 21 07:20:35 EDT 2005
Op 2005-04-21, Reinhold Birkenfeld schreef <reinhold-birkenfeld-nospam at wolke7.net>:
> Antoon Pardon wrote:
>> Op 2005-04-21, Reinhold Birkenfeld schreef <reinhold-birkenfeld-nospam at wolke7.net>:
>>> Antoon Pardon wrote:
>>>
>>>> I sometimes think python should have been more explicite here,
>>>> using a marker for the start-index and end-index, may '^' and
>>>> '$'. So if you wanted the last element you had to write:
>>>>
>>>> lst[$]
>>>>
>>>> And for the next to last element:
>>>>
>>>> lst[$ - 1]
>>>>
>>>>
>>>> This would make accessing list elements counted from the rear
>>>> almost just as easy as it is now but wouldn't interfere with
>>>> the ask forgiveness programming style.
>>>
>>> How would you pass this argument to __getitem__?
>>
>> Well assuming lst.last, was the last index of lst, __getitem__
>> would get lst.last and lst.last - 1 passed.
>
> Then it would be an alias for len(lst)-1 ?
In the context of current python lists yes. But if you would
go further and allow lists to start from an other index than
0 then not.
>>> What would be allowed, only '$-x' or also '$+x' or what else?
>>
>> Any expression where an int is allowed.
>
> Okay.
>
>>> What type would '$' be?
>>
>> It would be an int.
>
> Where would it be allowed? Only in subscriptions?
Yes, the idea would be that the brackets indicate a
scope where $ would be the last index and ^ would
be the first index. So if you wanted the middle
element you could do: lst[(^ + $) // 2]
But outsides the brackets the scope where this
has any meaning wouldn't be present.
Not that I think this idea has any chance. Already
I can hear people shout that this is too perlish.
But here is another idea.
Sometime ago I read about the possibility of python
acquiring a with statement. So that instead of having
to write:
obj.inst1 ...
obj.inst2 ...
obj.inst1 ...
You could write:
with obj:
.inst1 ...
.inst2 ...
.inst1 ...
If this would get implemented we could think of a left bracked
as implicitely exucting a with statement. If we then had a list
like class where the start-index could be different from zero and
which had properties first and last indicating the first and last
index we could then write something like:
lst[.last] for the last element or
lst[.last - 1] for the next to last element.
lst[.first] for the first element
lst[(.first + .last) // 2] for the middle element
Maybe this makes the proposal again pythonic enough to get
a little consideration.
--
Antoon Pardon
More information about the Python-list
mailing list