[Tutor] slice lists and slicing syntax questions

Alan Gauld alan.gauld at btinternet.com
Sat Oct 13 01:37:23 CEST 2007


<gregg at lind-beil.net> wrote

> in matrix oriented languages like R, Octave / Matlab, and NumPy, 
> vectors,
> lists, and matrices support slice lists of arbitrary indices.

Python is a general purpose language and not matrix oriented.
In fact it doesn't have native support for a matrix as such only
through add on modules such as numpy.

So not surprisingly normal python slicing doesn't do fancy tricks
As a recent thread on extended slicing shows numpy (and
potentially, other third party modules) can do fancy tricks with
slicing of multi dimensional structures, but they aren't 'standard'
python.

In fact, Python was the first language I had seen that treated
slicing as an operation and I thought it was really neat!
Up till then(~1997) I had always had to write functions to do that
(or use library functions if they existed).

> example:  x is vector of length 5, with value "a","b","c","d","e" , 
> then:
>
> x[3,1,1,1,3,2] # gives [d, b, b, b, d, c]
>
> What is the python equivalent?
>
> [a[j] for j in good_indices]

I think that's probably as close as you can get.
I can't think of anything more concise.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list