Learn how to

Slicing a list

The basic syntax of list slicing is:

a[start:stop:step]

Start, stop and step are optional. If you don’t fill them in, they will default to:

Here are some examples:

# We can easily create a new list from 
# the first two elements of a list:
first_two = [1, 2, 3, 4, 5][0:2]
print(first_two)
# [1, 2]

# And if we use a step value of 2, 
# we can skip over every second number
# like this:
steps = [1, 2, 3, 4, 5][0:5:2]
print(steps)
# [1, 3, 5]

Reversing a lists

revarray = [1, 2, 3, 4, 5][::-1]
print(revarray)
# [5, 4, 3, 2, 1]