🕯️ Magic Note
Slicing follows the pattern [start:stop:step]. When start and stop are omitted, Python uses the beginning and end of the sequence. A positive step moves forward from left to right. A negative step moves backward from right to left. The number determines how many characters to skip each time.
- Negative step means traverse from right to left
- The step value determines how many indices to move each time
- Step of 2 means take one, skip one, take one, skip one
- Works on strings, lists, and tuples
| Input String | Slice | Result |
|---|---|---|
| “mirror” | [::-1] | “rorrim” |
| “mirror” | [::-2] | “ror” |
| “mirror” | [::2] | “mio” |
| “mirror” | [1::2] | “irr” |
| “python” | [::-2] | “nhy” |
Python
# Every second character from the end
word = “mirror”
reflection = word[::-2]
print(reflection)
# Output: ror
Python
# Comparing forward and backward step slicing
text = “abcdefgh”
forward = text[::2]
backward = text[::-2]
print(f”Forward: {forward}”)
print(f”Backward: {backward}”)
# Output: Forward: aceg
# Output: Backward: hfdb
Python
# Custom start position with negative step
word = “magical”
result = word[5::-2]
print(result)
# Output: agm
- Confusing the direction when mixing positive and negative start values with negative steps
- Forgetting that step slicing creates a new sequence, not a view of the original
- Assuming a step of 0 works, Python raises a ValueError because step cannot be zero
⚡ Whisper
The mirror shows fragments. Not the whole face, but enough to recognize. Every second step reveals a new truth while shadows hide the rest. The reflection is honest but incomplete. That is the magic of the step slice.