Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Creating Custom Iterables

00:00 Now it’s time to create iterables. You know that iterables don’t have a __next__ magic method. For built-in iterables, Python implicitly creates an iterator for them.

00:14 But how can you create a custom iterable?

00:18 Let’s create a custom iterable class in Python that generates squares of numbers from one up to a specific maximum number.

00:28 First, you’re going to define a class that generates the squares of numbers. Let’s call it Squares class, Squares: Now you need to initialize the object with a list of squared numbers.

00:43 You’ll generate the squares in the __init__ magic method based on a max number that you pass in. Let’s do that def__init__ passing self and a max_number.

01:00 So you’re trying to generate a list of squares. It starts at one and then goes up to max_number squaring each number and then storing the result in self.items.

01:10 You can use a list comprehension for this: self .items = []. Let’s set an i and then power of two for i in range( So it starts from one and then goes up until max_number, which is the maximum number that will be squared plus one, and that’s it for the initialization.

01:41 Now you need to make your class an iterable, so you need to implement the __iter__ magic method self and then your returning iter(), the built-in function, and then self.items.

01:57 So when you use a for loop here on any instance of the Squares class, the iterator will internally call the next() function on the self.items and give you the squared numbers one by one.

02:12 Let’s create an instance of the Squares class. Let’s just call it squares with the lowercase ‘s’ instantiating from Squares.

02:23 And for themax_number, let’s put in 10. And now you can directly use a for loop here and access the items inside of square.

02:32 So for square in squares: print(square)

02:39 So you expect to see numbers from one to 10 squared, so like 1, 4, 9, 16, and so on. And let’s see if it works.

02:51 And it does. You got 1, 4, 9, 16, 25, 36, and so on up until a hundred. And as you can see here, your code works and you didn’t need to call the next function yourself.

03:07 Your custom iterable class just did it for you. To sum up, you use the __iter__ magic method here to create a custom iterable.

Become a Member to join the conversation.