Advertisement
Intermediate Python, Data Types & Structures

How do slicing operations work on a list, including negative indices and step values?

Short answer

list[start:stop:step] extracts a sub-list from index 'start' (inclusive) up to 'stop' (exclusive), advancing by 'step' — negative indices count from the END of the list, and a negative step reverses direction, letting you write concise expressions like list[::-1] to reverse a…

Save Python mock interview
Advertisement
AModel answer
list[start:stop:step] extracts a sub-list from index 'start' (inclusive) up to 'stop' (exclusive), advancing by 'step' — negative indices count from the END of the list, and a negative step reverses direction, letting you write concise expressions like list[::-1] to reverse a list entirely.
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:4])    # [1, 2, 3]
print(numbers[-2:])    # [4, 5] -- last two elements
print(numbers[::2])    # [0, 2, 4] -- every other element
print(numbers[::-1])   # [5, 4, 3, 2, 1, 0] -- reversed
Real-world example
Extracting a specific range of records or reversing an ordered list of results without a manual loop.
Likely follow-ups
  • Does slicing a list create a NEW list (a copy), or does it return a view into the original like NumPy arrays do?
Related topics