3S slice notation for Python arrays

"Climbing the Rocky steps" by Scott SM is licensed under CC BY-NC 2.0

Do you want to quickly select every nth element in a Python array? No problem, arrays in Python have built-in 3S property (aka slice notation), where you can specify start, stop and step to filter items in an array. Syntax is pretty simple, array[start:stop:step]. Implicitly if you don’t specify the property, Python will default to the largest unfiltered value and stop value is not included. Default stop value is length of the array, default start value is 0 and default step value is 1. Following snippet shows a few examples on a sample array.

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Select numbers smaller than 5 and larger than 1
[2, 3, 4]

# Print all even numbers except 0
[2, 4, 6, 8]

# Print all odd numbers reversed
[9, 7, 5, 3, 1]

# Python is nice in case you use an invalid index, it returns empty array


Popular posts from this blog

3 Must Haves of a Status Report

AWS encryption chart (SSE-S3 vs SSE-KMS vs SSE-C)

Configure hosts File in Android