How to Slice a List in Python: Syntax and Examples
In Python, you slice a list using the syntax
list[start:stop:step], where start is the index to begin, stop is the index to end (exclusive), and step is the interval between elements. This creates a new list with elements from the original list based on these positions.Syntax
The basic syntax for slicing a list is list[start:stop:step].
- start: The index where the slice starts (inclusive). Defaults to 0 if omitted.
- stop: The index where the slice ends (exclusive). Defaults to the length of the list if omitted.
- step: The interval between elements in the slice. Defaults to 1 if omitted.
Negative indices count from the end of the list, and negative steps reverse the slice direction.
python
my_list = [10, 20, 30, 40, 50] slice_example = my_list[1:4:2]
Example
This example shows how to slice a list to get every second element from index 1 to 4 (exclusive).
python
my_list = [10, 20, 30, 40, 50] slice1 = my_list[1:4:2] slice2 = my_list[:3] slice3 = my_list[3:] slice4 = my_list[::-1] print(slice1) print(slice2) print(slice3) print(slice4)
Output
[20, 40]
[10, 20, 30]
[40, 50]
[50, 40, 30, 20, 10]
Common Pitfalls
Common mistakes when slicing lists include:
- Using an end index that is out of range (Python handles this gracefully by stopping at the list end).
- Confusing
stopas inclusive instead of exclusive. - Forgetting that negative
stepreverses the slice direction. - Using a
stepof zero, which raises an error.
python
my_list = [1, 2, 3, 4, 5] # Wrong: step cannot be zero # slice_wrong = my_list[::0] # This will raise ValueError # Correct usage: slice_right = my_list[::-1] # Reverses the list print(slice_right)
Output
[5, 4, 3, 2, 1]
Quick Reference
| Slice Part | Description | Default Value |
|---|---|---|
| start | Index to start slicing (inclusive) | 0 |
| stop | Index to end slicing (exclusive) | Length of list |
| step | Step size between elements | 1 |
Key Takeaways
Use list[start:stop:step] to slice lists, where stop is exclusive.
Omitting start, stop, or step uses default values for easy slicing.
Negative indices count from the list end; negative step reverses the slice.
Avoid using step=0 as it causes an error.
Slicing creates a new list and does not modify the original.