![]() If you attempt to use the iterator that is already exhausted, you’ll get the StopIteration exception. It means you need to create a new iterator to iterate over its items again. Once you iterate over all the items, the iterator is exhausted. Then, use the for loop to iterate over items of the square iterator.First, create a new instance of the Square class.Print(sq) Code language: Python ( python ) The following shows how to use the Square iterator in a for loop: square = Square( 5) If the number of square numbers has been returned is greater than the length, the _next_ method raises the StopIteration exception. Third, implement the _next_ method that returns the next square number. Second, implement the _iter_ method that returns the self object. And the current attribute keeps track of the current integer. The length attribute specifies the number of square numbers that the class should return. Self.current += 1 return self.current ** 2 Code language: Python ( python )įirst, initialize the length and current attributes in the _init_ method. Self.current = 0 def _iter_ (self): return selfĭef _next_ (self): if self.current >= self.length: The following example defines Square iterator class that returns the square numbers. Python iterator exampleĪ square number is a product of an integer with itself. Python allows you to use iterators in for loops, comprehensions, and other built-in functions including map, filter, reduce, and zip. Note that these two methods are also known as the iterator protocol. If all the items have been returned, the method raises a StopIteration exception. _next_ method that returns the next item._iter_ method that returns the object itself. ![]() What is a Python iteratorĪn iterator is an object that implements: Summary: in this tutorial, you’ll learn about Python iterator and how to define a custom iterator using the iterator protocol. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |