Slicing (x[1:3])
A slice `x[start:stop]` gives you a new piece of a list, tuple or string, from `start` up to but not including `stop`.
Used in 106 lessons of the course, from 00.04.
A slice uses a colon inside the brackets: x[start:stop:step]. All three values are optional.
The key rule: start is included and stop is not. So x[1:3] returns the items at positions 1 and 2. This makes x[:3] have exactly 3 items, and x[:n] + x[n:] rebuilds the whole thing.
If you leave out start, it begins at the start. If you leave out stop, it goes to the end. Negative indexes work too: x[-2:] is the last two.
A slice always creates a new copy, and it never raises IndexError if you go past the length: it just returns what exists.
In the course you see it in [Path.cwd(), *Path.cwd().parents][:4]: a list of folders is built and [:4] keeps the first four, even if there are fewer.
letters = ["a", "b", "c", "d"]
print(letters[1:3])
Reach for it when: you need only part of a sequence: the first N items, the last N, or a stretch in the middle.
Examples
Common mistake
letters = ["a", "b", "c", "d"] print(letters[1:3]) print(letters[0:2] == [letters[0], letters[1], letters[2]])
Why: People expect `[0:2]` to include position 2, but the stop is excluded: it only brings positions 0 and 1.
How to write it: To include position 2, use [0:3]. The stop is the position after the last one you want.
Common mistake
letters = ["a", "b", "c"] print(letters[5])
Why: A plain index out of range raises an error. It gets confused with a slice, which is forgiving.
How to write it: Use letters[5:6] if you want an empty list instead of an error, or check the length first.
