Steps and Direction in a Slice
A slice step controls the spacing and direction of selected positions. Negative steps visit the sequence from right to left.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Follow a positive step
On "abcdef", [1:6:2] visits 1, 3, and 5 and produces "bdf". The excluded stop remains six. Arithmetic progressions in range give the same positions here.
Check a reverse visit
On the same string, [4:1:-1] visits 4, 3, and 2, giving "edc". The excluded position 1 follows the same slice boundary idea. An omitted boundary gets its interpretation from the step sign, so compare the intended positions before substituting an explicit stop.[1]
Compare phases of the same sampling step
On [0, 10, 20, 30, 40, 50], taking a stride of two from position zero yields [0, 20, 40]. Starting at position one produces [10, 30, 50]. Comparing these outputs as though they were measurements made at the same times introduces an offset. If positions encode samples every ten milliseconds, the two output streams share a twenty millisecond spacing but differ in their first sample time. See sequence slice boundaries to work out the last included position.
Work through a negative step with explicit indices
The slice values[4:0:-2] visits indices four and two. Position zero is excluded by the same endpoint rule, even though movement is toward the start. To include the beginning in a backward slice, Python lets the end remain omitted. A zero step does not describe movement and raises an error. Write down the expected positions before checking the values, especially when values repeat and hide an accidental skip. See counting with range.