Iterable class with a generator method

EasyIterator & Generator Programs · 8 of 20

Write a class whose objects can be looped over many times.

Advertisement
Output
['Song A', 'Song B'] ['Song A', 'Song B']

Approach

  1. Make __iter__ a generator; every loop gets a fresh one.

Solution

Python
class Playlist:    def __init__(self, *songs):        self.songs = songs     def __iter__(self):        for song in self.songs:            yield song p = Playlist("Song A", "Song B")print(list(p), list(p))
Output
['Song A', 'Song B'] ['Song A', 'Song B']

Learn the concept

New to this topic? Read the lesson, then come back.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Leave a Comment