[Tutor] 'slice', etc
Alan Gauld
alan.gauld at btinternet.com
Sat Dec 7 02:07:35 CET 2013
On 06/12/13 15:39, spir wrote:
> How does slicing in Python really work? Apparently, there are slice
> objects (start, past-end, step), generated using either the 'slice'
> builtin func or the extended slicing syntax [i:k:s]. Is this correct? [1]
I believe the slice notation simply calls the underlying method as is
the case for most operations in Python. But I'm no expert in the
internals, others are far better qualified.
> Does (only) the extended syntax (always) trigger slicing instead of
> contructing a new subsequence? (new substring or sublist or whatever,
> actually holding a section of the original sequence)
I'm not sure what you think slicing does? But in general a slice
produces a new sequence. Thus
L = [1,2,3,4]
L2 = L[1:2]
L2 is a new list object.
Indeed taking a full slice is one of the commonest ways of making a copy
of a list:
L3 = L[:] # a new copy of L
> Are slices and subsequences transparently usable one for the other?
subsequences don't exist as objects in Python so you can't use them in
the same way as a slice (which does explicitly exist). So I don't
understand what you have in mind here.
> rationale, design, etc... Maybe this means slices have always existed
> and I just missed them totally?
Slices have been in python since I started using it in V1.3. And I think
from before then too. Certainly a very long time.
> [2] The fact that slices exist at all shows how worth it is to avoid
> needlessly creating subsequences,
No it doesn't. Slices create new sequences.
Creating a "sub sequence" is often the fastest most efficient way to do
something. They are not something to get hung up about unless you have
absolutely proved they are a source of a problem. Especially given the
difficulty of writing reliable in-place code for many sequence operations.
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list