Lesson Contents
The Python slice() function allows us to slice a sequence. In plain English, this means we can retrieve a part of a string, tuple, list, etc. We can specify the start, end, and step of the slice. The step lets you skip items in the sequence.
This is the syntax:
[:]
: Items from the entire sequence.[start:]
: Items from start until the end of the sequence.[:stop]
: Items from the beginning until stop.[start:stop]
: Items from start until stop.[start:stop:step]
: Items from start until stop and skip items by step.
We specify the start, stop, and end with an integer. We can use positive and negative integers. This is best explained with some examples.
String Slicing
Consider the following string:
+---+---+---+---+---+---+---+
| G | i | g | a | b | i | t |
+---+---+---+---+---+---+---+
0 1 2 3 4 5 6 7
-7 -6 -5 -4 -3 -2 -1
We use the integers above as indices. You can see them as a pointer between the characters. For example:
- Integer 3 returns “a”.
- Integer -2 returns “i”.
Entire Sequence
This example doesn’t have any value, but it is valid Python:
This prints the entire string.
Start
Let’s slice and start at index 4:
Or slice and start with a negative index:
Stop
We can also slice from the beginning, until the stop:
Or with a negative index:
Start Stop
Let’s slice with a start and stop indices:
We can also do this with negative indices:
Start Stop Step
How about skipping some items? We can include a start, stop, and step:
Every other character is now skipped. We can also do this with negative indices:
That’s how we slice a string.
"Gigabit"[0:4]
is the same as "Gigabit"[slice(0,4)]
. The [] notation looks cleaner to me.List Slicing
Let’s try slicing a list. Here is an example with the indices:
+----+----+----+----+----+----+
| L0 | L1 | L2 | L3 | L4 | L5 |
+----+----+----+----+----+----+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
Entire Sequence
Let’s slice the entire sequence:
I can’t think of any valid reason why you might want to use this, but for the sake of completion, here it is.
Start
Let’s slice with a start and a positive integer:
Or slice with a negative integer:
Stop
We can also start from the beginning and specify a stop:
Or use a negative integer:
Start Stop
With start stop, we can select a range:
You can also do this with negative indices:
Start Stop Step
How about skipping some items with a step?
Which is also possible with negative indices: