Daily Code #0001
As a software developer, you’re probably extremely familiar with array notation syntax. Every major programming language has it; those familiar square brackets with a number in it, like
myArray. Python extends this concept significantly by adding two extra numbers to this syntax; end and step. Furthermore, it allows you to use negative indicies.
Let’s quickly cover how slice notation & negative indicies work before we explore some of the neat tricks it can do.
How Slice Notation Works
# retrieves item with index 5
# retrieves item's between index 1 & index 10 (but not index 10)
# retrieves every 2nd item between index 1 & index 10
# (but not index 10)
# returns the list item in the array
# returns the 3rd last item in the array
- Python slice notation is ordered as such:
start when used by itself in the format of
alist[start] returns the item with an index of
start . When used with an
end value in the format
alist[start:end] it specifies the index at which to start at (hence the name).
end when used by itself in the format
alist[:end] returns every item from the start of the array until
end-1 . That is
end is actually the first value not in the slice, as opposed to the last value that is in the slice. when used in conjunction with a start value it functions just the same —
alist[2:5] will return elements 2, 3 & 4 but not element 5 as element 5 is the first value to not be included in the slice.
step is used in order to skip elements — however people often get confused as to exactly how this works. When you say
alist[::2] , you’re not saying skip every 2nd element or take every 2nd element. You’re saying after the first element, skip one element, and then take the next. If you say
alist[::4] you’re saying after the first element, skip 3, and then take the next. It’s the inclusion of the first element at all times that makes the difference. You take the first element, skip
step -1 elements, and take the next value — rinse & repeat for the whole list or the range specified by
Negative indicies are used to specify access from the end of an array. And as you can’t have a negative 0, they’re actually 1 indexed. For example,
alist[-1] gets you the last element in the array and
alist[-10] will get you the 10th last element in the array.
Now that we’ve covered the basics of Python slice notation, let’s have a dive into some of most useful & practical applications.
- Reversing a list:
- Removing every nth element of the list
- Pop off the last n elements
- Shift the first n elements
- Get a list of numbers with index divisble by n