Lesson 1 ❮ Lesson List ❮ Top Page
❯ 1.6 Slice Operator
⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺
EXPECTED COMPLETION TIME
❲▹❳ Video 9m 8s
☷ Interactive readings 5m
To get a part (slice) of a list you can use the colon operator [start : end].
Note that the end index is NOT included in the list (exclusive) while the start index is included (inclusive). You can also use a negative index.
The following diagram helps to see how the slice works:
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
If you omit the first index in a slice (like foods[:3]), it will automatically start at the beginning of the list.
Similarly, you can omit the second index (like foods[2:]), if you want the rest of the list to be included.
The syntax of a Slice operator using double colon is [start : stop : steps].
start indicates the number from where the slicing will start,
stop indicates the number where the slicing will stop, and
steps indicates the number of jumps interpreter will take to slice the list.
To copy a list, you can use a slice of the original list with both indexes omitted (like this foods[:]). You can also use list.copy()
This is basically a copy of the original list.
In a slice, the colon acts as a binary operator, and should have equal amounts on either side (treating it as the operator with the lowest priority).
In an extended slice, both colons must have the same amount of spacing applied. Exception: when a slice parameter is omitted, the space is omitted.