Python slice notation explained

Created:

Introduction

Python slice notation is extremely powerful and very useful. This is a must have in your python skills. We will explain how to do slicing with python, for more details please read python docs.

Python Slice Examples

The slice notations is easy to understand. Let see some examples to understand it more easily:

elements = [1,'a',2,'b',3,'c']
start = 3
end = 5
elements[start:end] # it will return elements between 0 and 3. the result is [3]
elements[start:]    # elements from start position. result is [3, 'c']
elements[:end]      # items from the beginning through end-1. result is [1, 'a', 2, 'b', 3]
elements[:]         # shallow copy of the elements

Slice also a third parameter that allows to configure the step ( or stride). By default the value is one. As an example let's retrieve all integers (due to positions)

elements[0:6:2]
# this will return [1, 2, 3]

Negative integers are allowed as parameters. Using negative means that it cound from the end instead of the beginning

elements[-1]    # returns last item
elements[-2:]   # last two items
elements[:-2]   # everything except the last two items

Extended slices

More usages of slicing can be done if the first two parameters are not used. For example to reverse the elements of a list:

elements[::-1]
# will return ['c', 3, 'b', 2, 'a', 1]

However if we change the value -1 to -2:

elements[::-2]
# will return ['c', 'b', 'a']