python list index - an easy question
BartC
bc at freeuk.com
Sat Dec 17 17:53:43 EST 2016
On 17/12/2016 19:10, John wrote:
> Hi,
>
> I am new to Python, and I believe it's an easy question. I know R and Matlab.
>
> ************
>>>> x=[1,2,3,4,5,6,7]
>>>> x[0]
> 1
>>>> x[1:5]
> [2, 3, 4, 5]
> *************
>
> My question is: what does x[1:5] mean?
x[A:B] means the slice consisting of x[A], x[A+1],... x[B-1]. (Although
slices can shorter including those with be 0 or 1 elements.)
> By Python's convention, the first element of a list is indexed as "0".
Or the slice from the (A+1)th element to the B'th element inclusive, if
you are informally using ordinal indexing (first, second, third etc).
> Doesn't x[1:5] mean a sub-list of x, indexed 1,2,3,4,5?
Sublists and slices, once extracted, are indexed from 0 too.
Play around with some test code, but avoid test data containing numbers
that are not too different from possible indices as that will be confusing!
Strings might be better:
x = "ABCDEFGHIJKLM"
print (x[1:5])
displays: BCDE
print (x[1:5][0:2]) # slice of a slice
displays: BC
--
Bartc
More information about the Python-list
mailing list