How slicing in Python works
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Slicing is one of Python's most useful sequence features because it lets you select a range of items with very compact syntax. Once you understand how start, stop, and step interact, slices become predictable instead of magical.
The Core Rule
The general form is:
Python interprets that as:
- Start at
start - Move in increments of
step - Stop before reaching
stop
The most important detail is that stop is exclusive. That rule is why items[2:5] returns the elements at indices 2, 3, and 4, but not index 5.
Defaults and Negative Indices
If you omit start, Python uses the beginning of the sequence for a positive step. If you omit stop, Python uses the end. Negative indices count from the end of the sequence, where -1 means the last element.
Negative indices are just offsets from the end; they do not automatically reverse anything.
How step Changes the Slice
The step controls how far Python jumps between selected elements. A step of 2 means every second item. A negative step means traverse the sequence in reverse.
When the step is negative, the direction flips, so the start index should usually be to the right of the stop index. If those directions do not line up, the result is just an empty sequence.
Slice Objects Exist Explicitly
The bracket syntax is shorthand for a slice object. Python lets you create one directly and reuse it.
This becomes useful when the same slicing rule appears in several places, or when an API expects a slice object explicitly.
Slicing Returns a New Sequence
For built-in types such as lists, tuples, and strings, slicing returns a new object rather than a view into the original sequence.
That is why items[:] is a common shallow-copy pattern for lists.
One subtle point is that the copy is shallow. If the list contains nested mutable objects, those inner objects are still shared.
Slice Assignment on Lists
Lists support slice assignment, which lets you replace a whole range at once.
This is powerful, but it is specific to mutable sequences like lists. Strings and tuples do not support slice assignment because they are immutable.
Why Out-of-Range Slices Do Not Crash
Python clamps slicing boundaries gracefully. Asking for more than exists simply returns what is available.
That behavior is different from indexing a single element, where nums[10] raises IndexError.
Common Pitfalls
The most common mistake is forgetting that stop is exclusive. If you want the first five elements, the correct slice is items[:5], not items[:4].
Another issue is using a negative step with start and stop in the wrong order. items[2:7:-1] returns an empty result because Python cannot walk backward from 2 toward 7.
People also confuse slicing with deep copying. items[:] creates a new outer list, but nested mutable objects are still shared.
Finally, do not assume slicing is lazy. For built-in sequences, slicing usually allocates a new object, which can matter for large data structures.
Summary
- Python slicing follows
sequence[start:stop:step]. - The
stopbound is exclusive, which is the key rule to remember. - Negative indices count from the end, and negative steps reverse traversal.
- Slicing built-in sequences returns a new object, usually a shallow copy.
- List slicing also supports assignment, making it useful for in-place range updates.
Related reading
- "Least Astonishment" and the Mutable Default Argument
- Manually raising (throwing) an exception in Python
- Understanding Python super() with __init__() methods
- What is the difference between @staticmethod and @classmethod in Python?
- What is the difference between __str__ and __repr__?
- >, <, >= and <= don''t work with filter in Django
- __init__ got an unexpected keyword argument 'cachedir' when importing top2vec
- __str__ versus __unicode__
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.