Tuple slices

Nick Coghlan ncoghlan at iinet.net.au
Tue Jan 25 09:39:36 EST 2005

George Sakkis wrote:
> You're probably right about the allocation time, but my main concern is the memory required for each
> slice, which can be O(n) wrt the length of the whole tuple. I would like this to be constant (at
> least if there was a way around to the problem of deleting the underlying sequence).

If you really want a view into a tuple (or any sequence for that matter):

   from itertools import islice
   islice(iter(seq), start, end, step)

Then use the various functions in itertools to work with the resulting iterator 
(since the syntactic support for working with iterators is currently quite 
limited - slicing, concatenation and repetition are spelt with 
itertools.islice(), itertools.chain() and itertools.repeat(), rather than with 
their standard syntactic equivalents "[x:y:z]", "+" and "*").

The above approach does suffer from the problem of holding a reference to the 
original sequence, though.


Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia

More information about the Python-list mailing list