list · Python
items[i] and slicing
Reads or replaces one element by position; a slice returns a new list.
items[i]; items[i] = x; items[start:stop:step]
Complexity
| Best case | O(1) for one index |
|---|---|
| Worst case | O(k) for a slice of k elements |
| Extra space | O(1); O(k) for a slice |
An index is pointer arithmetic on the array. A slice copies k references into a new list.
Tested example
items = [1, 2, 3]
items[1] = 20
assert items[1] == 20
assert items[-1] == 3 # negative indices count from the end
assert items[0:2] == [1, 20] # a slice is a new list (a copy)
try:
items[3]
raise AssertionError("expected IndexError")
except IndexError:
pass
Parameters
- i
- -len ≤ i < len; negative counts from the end.
Behaviour
- Returns
- The element, or a new list for a slice.
- Errors and preconditions
- IndexError for an out-of-range index (slices never raise; they clamp).
- Changes
- Assignment replaces an element; slice assignment can change the length.
- Memory and invalidation
- A slice allocates a new list (shallow copy).