Python: Slices

by Brian Hines
  python

If you work with Python often, slicing a list is something you’ve done countless times. By now you’ve probably done it so much you don’t think about it. However, I recently spent time, with a few books, digging into the standard library and I learned (or was reminded of) a couple things regarding slices.

Named Slices

If you need to use the same ranges over and over for slicing, you can assign them to variables creating reusable, named slices. The subscript notation we are familiar with ([start:stop:step]) uses the built-in function slice under the hood. For example:

my_slice = slice(1,3)

numbers = [1, 2, 3, 4, 5]

numbers[my_slice] == numbers[1:3]  # True

IndexError or not

Pop quiz hotshot: given the same list above (numbers), what happens when you do this?

numbers[5]

Well duh, that throws an IndexError. Indeed it does.

How about this?

numbers[3:10]

The index for 3 exists, but 10 doesn’t so that’s another IndexError, right? Wrong, slicing is more forgiving than accessing a single index so the result here is actually [4, 5].

Ok, what about this?

numbers[5:10]

Both the start and stop index in the slice are beyond the range of the list, so this has to throw an error. Wrong again, the result here is an empty list.