slice notation as values?

Duncan Booth duncan.booth at invalid.invalid
Fri Dec 9 08:45:42 EST 2005


Antoon Pardon asked:


> If we have lst = range(10), we can write
> 
>    lst[slice(3,7)]
> 
> instead of
> 
>    lst[3:7]
> 
> Now my impression is that should we only have the upper notation, slices
> would be less usefull, because it would make using them more cumbersome.

Quite right, but the syntax for the slice only applies inside the square 
brackets and there would be big problems making it work outside a 
subscript. If you allowed a:b you get syntactic ambiguities: e.g. is this a 
slice or a complete if statement:

   if a:b

If you allow a slice on its own but require the square brackets still to be 
there then you don't (I think) get any syntax ambiguities, but the result 
looks like it should be some weird list comprehension so its just too 
confusing:

   myslice = [a:b]

I think the case for freestanding slices is there, but they aren't common 
enough to justify special syntax.

> If the user can write:
> 
>   for key in tree['a':'b']:
> 
> Why shouldn't he be able to write:
> 
>   for key, value in tree.iteritems('a':'b'):
> 

>>> import this
...
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
...

If the user can write

   for key in tree['a':'b']:

then he can write:

   for key in tree['a':'b'].iteritems():

so why add a second way to do that?





More information about the Python-list mailing list