What Is A Slice ?
A slice of a python list is segment of the list. The original list still retains all it's elements when that slice is taken out of it.
Example 1
We have the following list of even numbers from 2 - 100.
even_nums = [2, 4, 6, 8, 10, 12, 14, ..., 100]
This is a slice of the first three elements.
[2, 3, 5]
This is a slice of the last five elements.
[92, 94, 96, 98, 100]
A slice can be the full list too.
[2, 4, 6, 8, 10, 12, 14, ..., 100]
Why Do We Need Slices ?
Simple. You need slicing when you want to work with a segment of the list and not the full list. Note that a segment of a list is a list too.
Example 2
You got a side gig to help a school create a student scoring program. You take a list of scores and calcute the overall total score for each student. Now that you have a list of the total scores, you need to get the top five scores.
assume that the list of total scores is sorted from higher scores to lower scores.
total_scores = [95, 93, 92, 87, 81, 73, 72, 70, 63, 61, 54]
This is a slice of the top five scores.
top_five_scores = [95, 93, 92, 87, 81]
Slicing Like A Chef ๐จโ๐ณ๐ช
Just like every chef needs to be skillful with knifes to be great at his/her job, you also need to get good at slicing to be efficient at handling segments of a list.
Square brackets ([]
) is a handly python operator used to slice lists. The square brackets are placed right after the variable name like this: a_list[]
.
Let me explain how the operator works works.
slicing the first n elements
You can do this by placing a colon (:
) followed by a number inside the square brackets ([]
). The number after the colon represents the number of elements you want in the segment.
a_list = [...]
# to select first 10 elements
first_10 = a_list[:10]
Let's bring back Example 2, where you want to get the top five scores. Programmatically, the problem can be solved like this.
total_scores = [95, 93, 92, 87, 81, 73, 72, 70, 63, 61, 54]
top_five_scores = total_scores[:5]
print(top_five_scores)
# output
[95, 93, 92, 87, 81]
start slicing from a different position
By default, slicing starts from the first element in the list. This means that when you slice out five elements, the segment would contain all elements from a_list[0]
to a_list[4]
(_not a_list[5]
because list indexing starts from zero_).
This behavior can be changed by supplying an index to start from. Do this by put a number followed by a colon :
inside the square brackets []
. The number before the colon represents the index you want to start from.
a_list = [...]
# select from the 5th element (index 4)
from_fifth = a_list[4:]
slice first n elements from a given index
You can slice first n elements right? You can also slice from a given index right? Now can you mix them both?
The secret is understanding that the colon (:
) is really just a separator, therefore the syntax looks like this
a_list[start:stop]
a_list
is a liststart
is the index to start the splitting fromstop
is the index to stop splitting at.NOTE:
stop
is non-inclusive, meaning that the element at indexstop
would not be included in the returned segment.
Example 3
You have a list of names sorted in alphabetical order, now select the first two names starting with "b".
names = ["Aaliyah", "Abby", "Abigail", "Ada", "Bailey", "Bella", "Blair", "Bonnie", "Brylee", "Cali", "Cara", "Caroline", "Casey", "Celia", ...]
- you know that 'a' names end at index 3 and 'b' names start at index 4. So your
start
is 4. - you know you're selecting two names starting from index 4, so your
stop
isstart
+ 2, which is 6.
two_b_names = names[4:6]
print(two_b_names)
# output
["Bailey", "Bella"]
skipping elements when slicing
Slicing allows you to specify how many steps you like to take at a time. By default, it takes one step at a time. Imagine you have a list of integers from 1 to 100, and you need to get all even numbers, what would you do?
So the syntax for slicing looked like this before,
a_list[start:stop]
but this isn't the full syntax. The full syntax looks like this.
a_list[start:stop:step]
step
is the length of the stride while slicing from start
to stop
. A step of two means if one element is selected, the one next to it skipped.
Example 4
You have a list of integers from 1-100, you need to separate even and odd numbers, each one in a different list.
numbers = [1, 2, 3, 4, 5, 6, ..., 99, 100]
For even numbers,
You know the first even number is at index 1, so
start
is 1You want to stop at the end of the list, so leave
stop
as the default (the default is the end of the list)You know you want to select one element and skip the next, so set
step
to be 2.
even_numbers = numbers[1::2]
print(even_numbers)
# output
[2, 4, 8, 10, ..., 98, 100]
NOTICE: there's nothing in the place where
stop
should be.
For odd numbers,
You know the first odd number is at index 0, so
start
is 0You want to stop at the end of the list, so leave
stop
as the default (the default is the end of the list)You know you want to select one element and skip the next, so set
step
to be 2. ```py odd_numbers = numbers[0::2]
print(odd_numbers)
output
[1, 3, 5, 7, ..., 97, 99]
You can also leave out `start` entirely, since by default, `start` is 0.
```py
odd_numbers = numbers[::2]
print(odd_numbers)
# output
[1, 3, 5, 7, ..., 97, 99]
defaults for start, step and stop
The default for start
is always 0.
The default for step
is always 1.
The default of stop
is usually the length of the list, which is the last element's index + 1. The reason for this is because stop
is non-inclusive, the index specified by stop
would not be included in the slicing.
What Else Can Be Sliced?
Lists, tuples and strings can be sliced using the same operator and syntax.
- slicing a string returns a string
- slicing a list returns a list
- slicing a tuple returns a tuple