What does slicing a string cost?
A slice is a copy, never a view. s[2:6] allocates a new string and copies four characters, so slicing is O(k) in both time and memory for a slice of length k. One slice is free; a slice per iteration is how an O(n) scan quietly becomes O(n²).
Overview
Copy, not view
Some languages hand you a slice that points into the original buffer, so taking one is O(1). Python does not: s[2:6] allocates a new string object and memcpys four characters into it. The cost is proportional to the slice, not to the original.
You can prove it from the interpreter: the id differs, and mutating is impossible anyway, so there is no aliasing to observe. What you can measure is the time, which is what the editor below does.
Step through it
What to watch
- The second row is a separate object, not a window into the first.
s[::-1]copies the whole string — fine once, expensive in a loop.- Compare with
memoryview, which really is a view — but only overbytes.
Say this out loud
"Slices copy. It's O(k) time and space for a k-length slice, so inside a loop I carry indices instead of slicing."