Making a container

Special methods let your class work with built-in syntax:

  • __len__ for len(p). It also makes an empty object falsy in if p:.
  • __getitem__ for p[0], p[-1] and p[1:3].
  • __iter__ for for song in p, list(p) and enumerate(p).
  • __contains__ for "verse" in p.

The easy way is to delegate: keep a list inside and pass each call on to it. Slicing works for free because the list handles the slice object.

Even without __iter__ and __contains__, Python can loop and test in using __getitem__ alone. Writing them is clearer and faster.

Watch the cost of __contains__: here it searches a list, which is O(n). If the class is checked often, keep a set alongside for O(1) lookups, as the Performance challenges show.

Run it, then make __getitem__ raise for negative indexes.