a possibly foolish question about slices

holger krekel pyth at devel.trillke.net
Mon Jun 17 06:34:41 EDT 2002


Michael Hudson wrote:
> garth at deadlybloodyserious.com (Garth T Kidd) writes:
> 
> > > x[p:][:n]
> > 
> > Does the parser take the appropriate short-cut, here,
> 
> No.  Wouldn't be the parser anyway, would it?
> 
> > or do we end up with a temporary list?
> 
> It's very easy to answer questions about whether Python performs this
> sort of optimization: it doesn't.

:-)

[michael probably knows the following, nevertheless]

python's compiler can't possibly optimize unless it somehow had 
additional information about the *name* where an object is 
bound to. As things stand the names 'x','p','n' in the above expression
could point to almost any object with as many sideeffects as imaginable.
More specifically in 'x[p:]' the slice-operator of the object denoted by 'x' 
could have sideeffects which the compiler can't try to guess.

on the flip side you get the powerful dynamisms of python which spares
time in many other respects :-)

seriously though, the above expression is not very nice if 'x' is a
big list. It then executes *much much* slower compared to something like:

def numslice(x, start, maxnum):
    end=start+maxnum
    if start<0 and end>=0:
        return x[start:]
    return x[start:end]

Plus this also makes it possible to let

    numslice(x, -5, 10)

return the last 5 elements.

cheers,

    holger





More information about the Python-list mailing list