Slicing lists

A slice takes a range of a list: nums[start:stop:step]. Like range, the stop is not included, so nums[2:5] gives positions 2, 3 and 4.

Leave a part out to use the default. nums[:3] is the first three items, nums[-3:] is the last three, and nums[::2] is every second item. A negative step walks backwards, so nums[::-1] is a reversed copy.

Three facts that come up in interviews:

  • A slice is a new list. nums[:] is the short way to copy a list.
  • Slices never raise IndexError. nums[5:100] just stops at the end.
  • Assigning to a slice replaces that part, and can change the length: nums[1:4] = ["a", "b"].

Slicing costs O(k) for a slice of k items, because it copies them. Slicing inside a loop can quietly make code O(n²).

Run it, then try nums[8:2:-2] and predict the result first.