Wednesday, November 09, 2005

array slices

A good way to think of the negative indices of array slices:

>> spam = 'spam' * 5;
>> spam[-1] <--- this is essentially spam[len(spam) - 1]
>> spam[-4:-2] <-- this is [len(spam) - 4: len): len(spam) - 2]

Also, how can you remember if
spam[1:2] means element 1 and 2 or element 1 only?

A good way to remember this is to imagine you are cutting a cake, and both indices indicate the border that you should cut it at, with the border index starting from 0 for the first slice. So instead of thinking 1 as cake slice #1, think of it as the left side of slice #1, and 2 as the right side of slice #1. So you are getting slice 1 of the cake after this operation.

So to recap:
spam[0] - you are taking the whole slice
spam[0:2] - you are slicing the cake at border 0 and border 2. So you get element 0 and 1.

0 Comments:

Post a Comment

<< Home