Python Snippets #0 - Array Slicing

Python Snippets #0 - Array Slicing

This is the first of an ongoing and probably infrequent series on Python snippets, or short, basic hints for Python to make your developer life easier.

This one is incredibly basic: array slicing!

Array slicing, or the syntax to create sub-arrays from input arrays, is an incredibly useful concept that I learned... way too late in my programming career.

array1 = [1,1,2,3,5,8,13,21,34]
array2 = array1[1:5] # [1,2,3,5]
array3 = array1[:2] # [1,1]
array4 = array1[1:] # [1,2,3,5,8,13,21,34]

In the above code snippet, the original array is loaded with values (the first couple of values in the Fibonacci sequence) and each subsequent array is a slice of the original array.

  • array2 takes all of the values from the second value (index 1) to the fourth value (index 5, non-inclusive).
  • array3 takes all values from the first (index 0, implied by the lack of an index on the left of the colon) to the second value (index 2, non-inclusive).
  • array4 takes all values from the second value (index 1) to the end.

The syntax can be remembered this way:

arraySlice = sourceArray[firstIndex_Inclusive:lastIndex_NonInclusive]

The most difficult part of this syntax is memorizing that the ending index is non-inclusive. This has lead to plenty of unfortunate bugs on my part...