slice notation as values?

Duncan Booth duncan.booth at invalid.invalid
Sat Dec 10 11:03:03 EST 2005


Antoon Pardon wrote:
> In general I use slices over a tree because I only want to iterate
> over a specific subdomain of the keys. I'm not iterested in make
> a tree over the subdomain. Making such a subtree would be an
> enormous waste of resources. 

Probably not unless you have really large data structures. If you have 
something like a dbhash which would be inefficient to copy then both the 
original view of the data structure and the slices could share the same 
data. Creating a slice doesn't *have* to copy anything just so long as the 
semantics are clear.

> With slice notation you could have the following two cases:
> 
>   for key in tree.iterkeys('a':)
> 
>   for key in tree.iterkeys(:'b')

 x['a':] is short for x['a':None]
 x[:'b'] is short for x[None:'b']

> 
> But you can't do
> 
>   for key in tree.iterkeys('a',)
> 
> or more regrettably, you can't do:
> 
>   for key in tree.iterkeys(,'b')

If your datatype defines iterkeys to accept start and end arguments then 
you can do:

   for key in tree.iterkeys('a',None)
   for key in tree.iterkeys(None,'b')

which is directly equivalent to the slices, or you can do:

   for key in tree.iterkeys(start='a')
   for key in tree.iterkeys(stop='b')

which is more explicit.

> I also think that other functions could benefit. For instance suppose
> you want to iterate over every second element in a list. Sure you
> can use an extended slice or use some kind of while. But why not
> extend enumerate to include an optional slice parameter, so you could
> do it as follows:
> 
>   for el in enumerate(lst,::2)

'Why not'? Because it makes for a more complicated interface for something 
you can already do quite easily.



More information about the Python-list mailing list