Slicing Elements of Array

This is supposed to be a concise tutorial and you should not spend longer than 10 minutes to go through it.

Idea

L = range(10)
>> L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

We can slice as L[startAt:endBefore:skip] where indices live BETWEEN elements.


Example 1: Suppose we want every 3rd element.

L[::3]
>> L = [0, 3, 6, 9]


Example 2: Suppose we want every 3rd element, starting from the first one

L[1::3]
>> L = [1, 4, 7]


Example 3: Suppose we want every 3rd element, starting from the second one

L[2::3]
>> L = [2, 5, 8]


Example 4: We can specify a negative step to go backwards

L[::-1]
>> L = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]


Example 5: We can delete every 3rd element

del L[::3]
>> L = [1, 2, 4, 5, 7, 8]

References

This tutorial is summarized and is revised from:

Other blogged posts >> Tutorials