How to index an array with even steps?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Jul 25 07:55:39 EDT 2014


On Fri, 25 Jul 2014 04:45:31 -0700, fl wrote:

> Hi,
> 
> I have an array arr which is indexed from 0 to 999. I would like to
> construct a column in two steps. The first step is input from 200 data,
> evenly spread from 0 to 999 of the target array. Then, I want to use
> interpolate it from 200 to 1000 with interpolate method.
> 
> In Python, ':' is used to indicate range (while in Matlab I know it can
> be used to control steps). How to index an array with 0, 5, 10,
> 15...995?

You can take a slice of the array and specify the step size. This works 
with lists, tuples, arrays and strings. For convenience, I will use 
strings, since there is less typing:

py> data = "abcdefghijklmnopqrstuvwxyz"
py> data[::5]
'afkpuz'
py> data[::3]
'adgjmpsvy'


You can specify a slice using any combination of:

    start : end : step


If you leave the start out, it defaults to 0, if you leave the end out, 
it defaults to the end of the string or list, and if you leave the step 
out, it defaults to 1.


Similarly, range() takes up to three arguments:

range(end)
range(start, end)
range(start, end, step)



-- 
Steven



More information about the Python-list mailing list