Lesson 4 of 10

A class that acts like a list

Goal

len, in and for on your own class

01

Explanation

len(x), x[0], "a" in x and for s in x aren't special to lists. Each one calls a special method on the class: __len__, __getitem__, __contains__ and __iter__, in that order. Define them in your class and Python treats it just like a list.

The payoff is that people using your class don't have to learn new methods like get_song(0) and count(), and they get everything built on these methods for free, such as sorted, list and enumerate. An empty playlist even counts as False in if playlist:, just like a regular list.

The trap in __iter__ is that it must return a fresh iterator on every call. Make the class its own iterator and the second loop comes up empty, because the first one used it up. The simplest fix is to leave this to the inner list, which hands out a new iterator whenever it's asked.

02

Your task

Add all four methods to Playlist, building on self.songs, so the class works with len, indexing by position, in and for.

Checks

6 checks
  1. len counts the songs
  2. Indexing works from both ends
  3. The in operator searches the songs
  4. A for loop visits the songs in order
  5. Works in more than one loop
  6. An empty playlist is False in an if
main.py
OutputPython (Pyodide)

Loading Python. This only happens once. Your browser keeps it after that.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.