first and last index as in matlab

sturlamolden sturlamolden at yahoo.no
Sun Dec 17 18:10:48 EST 2006


It's quite straight forward, actually. What you need to know is that -1
is the index of the last element in a sequence, and that slicing
excludes the 'end' value in 'start:end'. So if you type arr[0:N], you
get the subsequence

[arr[0], arr[1], arr[2], ..., arr[N-1]]

When comparing with Matlab, Python slicing works like this:

arr(1:end)   ->  arr[:] or arr[0:]
arr(1:end-1)  -> arr[:-1] or arr[0:-1]
arr(1:end-N) -> arr[:-N] or arr[0:-N]
arr(end)  -> arr[-1]
arr(1)  ->  arr[0]
arr(1:2:end)  ->  arr[::2] or arr[0::2]
arr(1:2:end-1)  -> arr[:-1:2] or arr[0:-1:2]

Python slicing is not completely like Matlab, because it was adoped
from Haskell. It can do the same as Matlab's indexing, but the syntax
is different. If you think Matlab's indexing is more intuitive it is
just because you are more used to it.




More information about the Python-list mailing list