🕯️ 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 step of 1 moves forward. A step of -1 moves backward. This works on any sequence, not just strings.
- Works on any sequence: strings, lists, tuples
- Creates a new reversed object, does not modify the original
- Can reverse with custom start and end positions: text[4:1:-1]
- For lists, reversed(list) returns an iterator, while list[::-1] returns a new list
| Input | Slicing | Output |
|---|---|---|
| “Hello” | “Hello”[::-1] | “olleH” |
| “madam” | “madam”[::-1] | “madam” |
| “Python” | “Python”[::-1] | “nohtyP” |
| [1, 2, 3, 4] | [1, 2, 3, 4][::-1] | [4, 3, 2, 1] |
| (“a”, “b”, “c”) | (“a”, “b”, “c”)[::-1] | (“c”, “b”, “a”) |
Python
# Reversing a string
word = “whisper”
backwards = word[::-1]
print(backwards)
# Output: repsihw
Python
# Checking for palindromes
def is_palindrome(text):
cleaned = text.lower().replace(” “, “”)
return cleaned == cleaned[::-1]
print(is_palindrome(“A man a plan a canal panama”))
# Output: True
print(is_palindrome(“python”))
# Output: False
Python
# Partial reverse with custom start and stop
text = “programming”
partial = text[4:8:-1]
print(partial)
# Output: “rg”
# Walk backward from index 7 to 4 (not including 4)
- Forgetting that [::-1] creates a new copy, thinking it reverses in place
- Using [::-1] on integers, this only works on sequences not numbers
- Confusing reversed() (returns iterator) with [::-1] (returns new sequence)
⚡ Whisper
The mirror does not change what it reflects. It only shows the other side. Your original string remains. The reversed version is a whisper from the end of time, reading backward to reveal what was hidden.