PythonPython ListsPython list slicing
How does list slicing work?
Question 79 of 88 · Updated
On this page
List slicing extracts part of a list using items[start:stop:step]. It includes the start index, excludes the stop index, and uses a step of 1 by default. Reading a slice creates a new list without changing the original.
Example: Select days from a schedule#
PYTHONdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] print(days[1:4]) # ['Tue', 'Wed', 'Thu']
| Index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Day | Mon | Tue | Wed | Thu | Fri |
| Selected | No | Yes | Yes | Yes | No |
The slice starts at index 1 and stops just before index 4.
Useful slicing patterns#
Using the same days list:
| Expression | Result | Practical use |
|---|---|---|
days[:2] | ['Mon', 'Tue'] | First two days |
days[-2:] | ['Thu', 'Fri'] | Last two days |
days[::2] | ['Mon', 'Wed', 'Fri'] | Every other day |
days[::-1] | ['Fri', 'Thu', 'Wed', 'Tue', 'Mon'] | Reverse order |
days[:] | All five days | Shallow copy |
Negative indexes count from the end. A negative step moves backward; with omitted bounds, [::-1] reverses the whole list.
Does slicing change the original list?#
PYTHONdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] copy = days[:] copy[0] = 'Sun' print(days[0]) # Mon
The outer lists are separate. However, slicing is a shallow copy: nested mutable objects remain shared. Changing a nested list through the copy can affect the original.
Slice assignment, such as days[1:3] = ['Holiday'], is different: it modifies the original list.
Common mistakes#
- Expecting the stop index to be included.
- Assuming an out-of-range slice raises IndexError:
days[3:99]returns ['Thu', 'Fri'], whiledays[9:]returns an empty list. - Using a zero step:
days[::0]raises ValueError. - Confusing a single index with a slice:
days[0]returns a string, whereasdays[:1]returns a list.
Try it yourself#
What does days[2:2] return?
Answer: an empty list, because the start and stop are equal.
Interview takeaway: A list slice selects a range of elements, with an exclusive stop and optional step. For an ordinary CPython list, producing a slice of k elements takes O(k) time and O(k) additional reference storage.
Official references#
References
- 1.Python Tutorial — Listsdocs.python.org
- 2.Common sequence operationsdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design