Python List Slicing: Syntax, Patterns, and Pitfalls
Learn how to use Python list slicing to extract subsequences, modify lists, and handle edge cases with clear examples and performance notes.

Python list slicing is a concise way to extract a subsequence from a list. The syntax list[start:stop:step] returns a new list containing elements from the original list, starting at start, ending before stop, and advancing by step. This operation is used everywhere in Python code, from simple data extraction to complex algorithmic patterns.
Basic Syntax of Python List Slicing
The slice operator uses square brackets with colon-separated parameters. All three parameters are optional. With a positive step, an omitted start defaults to 0, an omitted stop defaults to the length of the list, and step defaults to 1. For example:
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
subset = numbers[2:7]
print(subset) # [2, 3, 4, 5, 6]The start index is inclusive, while the stop index is exclusive. This matches the behavior of range() and avoids off-by-one errors when chaining slices.
With a positive step, the omitted values default as follows:
| Parameter | Default | Meaning |
|---|---|---|
start | 0 | First index to include |
stop | len(list) | Index to stop before |
step | 1 | Increment between indices |
When step is negative, the defaults are reversed: an omitted start is the last element, and an omitted stop is before the first element. This is why [::-1] returns a reversed copy.
When step is omitted, the slice is a contiguous block. When step is greater than 1, the slice skips elements.
Using Negative Indices and Steps
Negative indices count from the end of the list. -1 refers to the last element, -2 to the second-to-last, and so on. This is particularly useful for extracting the tail of a list:
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
last_three = numbers[-3:]
print(last_three) # [7, 8, 9]The step parameter can also be negative, which reverses the traversal direction. A step of -1 returns a reversed copy of the list:
reversed_list = numbers[::-1]
print(reversed_list) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]Combining a negative step with explicit start and stop indices requires care because the start index must be greater than the stop index for the slice to be non-empty. For example, numbers[8:2:-2] yields [8, 6, 4].
Slice Assignment: Modifying Lists in Place
Slicing is not limited to reading data. You can assign to a slice to replace, insert, or delete elements in the original list. For a contiguous slice (with step omitted or equal to 1), the assigned value must be an iterable, and its length does not need to match the slice length. If the slice uses a step other than 1, the replacement must have the same length as the number of elements being replaced.
numbers = [0, 1, 2, 3, 4, 5]
numbers[1:4] = [10, 20]
print(numbers) # [0, 10, 20, 4, 5]If the replacement iterable is shorter than the slice, the list shrinks. If it is longer, the list grows. To insert elements without removing anything, use a slice with equal start and stop indices:
numbers[2:2] = [99]
print(numbers) # [0, 10, 99, 20, 4, 5]To delete a segment, assign an empty list:
numbers[1:3] = []Slice assignment is a common way to implement in-place transformations without creating a new list object.
Common Patterns: Copying, Reversing, and Extracting
Several idiomatic patterns rely on slicing:
- Copy a list:
new_list = original[:]creates a shallow copy. This is often clearer thanlist(original)for lists. - Reverse a list:
reversed_list = original[::-1]returns a new reversed list. For in-place reversal, useoriginal.reverse(). - Extract every nth element:
every_third = original[::3]collects indices 0, 3, 6, etc. - Remove the first and last elements:
middle = original[1:-1]is useful for trimming boundaries.
These patterns appear frequently in data processing and algorithm implementations. Because slicing creates a new list, the original remains unchanged unless you explicitly assign to a slice.
Performance and Memory Behavior of Slicing
Each slice operation allocates a new list and copies references to the selected elements. The time complexity is O(k), where k is the number of elements in the slice. The memory usage is also O(k), because the new list stores references to the same objects, not copies of the objects themselves.
For large lists, creating many slices can lead to significant memory overhead. If you only need to iterate over a subsequence, consider using itertools.islice to avoid materializing a new list:
from itertools import islice
data = list(range(10))
for item in islice(data, 2, 7):
print(item)However, islice does not support negative indices or steps. When you need a concrete list for further processing, slicing is the straightforward choice.
Edge Cases and Common Mistakes
Several pitfalls can trip up developers new to slicing:
- Out-of-range indices are silently clamped.
numbers[5:100]returns elements from index 5 to the end, andnumbers[100:200]returns an empty list. This is intentional but can hide bugs if you expect an error. - A step of zero raises
ValueError. The slicenumbers[::0]is invalid because the step cannot be zero. - Slicing does not create a view. Unlike NumPy arrays, Python lists are not backed by a shared buffer. The new list is independent, and modifying it does not affect the original.
- Confusing
copywith slicing.list.copy()andoriginal[:]are equivalent for shallow copies. Butcopy.deepcopyis needed for nested structures.
Understanding these behaviors helps you use slicing confidently without unexpected results.
Using Slicing for List Rotation
A common interview and practical problem is rotating a list by k positions. Slicing provides a compact solution:
def rotate(lst, k):
if not lst:
return lst[:]
k %= len(lst)
return lst[-k:] + lst[:-k] if k else lst[:]The function normalizes k to avoid unnecessary rotations, then concatenates the last k elements with the remaining prefix. This creates a new list, so the original is unchanged. If you need to rotate in place, you can use slice assignment:
def rotate_in_place(lst, k):
if not lst:
return
k %= len(lst)
if k:
lst[:] = lst[-k:] + lst[:-k]The empty-list guard prevents k %= len(lst) from raising ZeroDivisionError. The slice assignment lst[:] replaces the entire list content, preserving the original object's identity. This pattern keeps the same list object and stays readable for array-manipulation tasks.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.