Table of Contents
This guide covers iterator object in python with practical context and easy-to-follow details. Use it to understand the subject and apply the information confidently.
Iterator is everywhere in Python, inside loops, comprehension, generator.
It is simply objects that allow us to retrieve each element, whenever you use loops or techniques to get the value of an element group at a given time.
Technically, Python in Python must implement two special methods: __iter __ () And __next __ (), Collectively referred to as the iterator protocol (Iterator Protocol).
- The __iter__ Method returns the iterator object itself. This method is required to install both "iterable" and iterator objects to use for and print statements.
- The __next__ Method returns the next element. If there are no more elements, a StopIteration error will occur.
Iterable objects Are an object after using methods that will return an iterator, such as String, List, and Tuple.
Iter () Is a built-in function in Python that takes the input as an iterable object and returns an iterator.
# Khai bao mot listmy_list = [4, 7, 0, 3]# lay mot iterator bang cach su dung iter()my_iter = iter(my_list)## su dung next()#prints 4print(next(my_iter))#prints 7print(next(my_iter))## next(obj) chinh la obj.__next__()#prints 0print(my_iter.__next__())#prints 3print(my_iter.__next__())## Xay ra loi StopIteration vi het gia tri tra venext(my_iter)
Run the program, the result is:
4703Traceback (most recent call last):File "", line 24, innext(my_iter)StopIteration
A similar way to return this result is to use a For Loop .
>>> for element in my_list:. print(element).4703
As we see in the above example, the For Loop can be repeated automatically through the use of the list.
In fact, the For Loop can be repeated on any iterable. Let's take a closer look at how a for loop is implemented in Python.
for element in iterable:# do something with element
Made similar to:
# iter_obj là m?t iterator object t?o t? iterableiter_obj = iter(iterable)# vòng l?pwhile True:try:# s? d?ng nextelement = next(iter_obj)except StopIteration:# n?u x?y ra l?i StopIteration thì vòng l?p s? ???c break ra ngoàibreak
In this example, inside the For Loop we create an iterator object called Iter_obj By calling Iter () On iterable.
And as you can see, the for loop here is an infinite while loop Next () Inside the loop retrieves the elements to execute commands in For Loop. When all values are taken, the StopIteration exception will be generated and the loop will end.
You can build the iterator as a class. Building an iterator is easy in Python, we only need to implement __iter __ () And __next __ () methods.
class PowTwo:def __init__(self, max = 0):self.max = maxdef __iter__(self):self.n = 0return selfdef __next__(self):if self.n <= self.max:result = 2 ** self.nself.n += 1return resultelse:raise StopIteration
The __iter__ Method will cause the object to become an iterable object.
The return value of __iter__ Is an iterator. It needs a __next__ Method and returns StopIteration If there are no more tests.
Create an iterator and run the program as follows:
>>> a = PowTwo(4)>>> i = iter(a)>>> next(i)1>>> next(i)2>>> next(i)4>>> next(i)8>>> next(i)16>>> next(i)Traceback (most recent call last):.StopIteration
You can also use a for loop to iterator iterators
>>> for i in PowTwo(5):. print(i).12481632
Iterator Iterates Infinitely in Python
Not all iterator objects will be called all elements and end when there are no elements left. There are some iterator instances that will loop infinitely. Examples are as follows:
>>> int()0>>> inf = iter(int,1)>>> next(inf)0>>> next(inf)0
You can see that the Int () Function always returns 0. Therefore, passing it in Iter (int, 1) Will return an iterator until the value returns to 1. This is never happens and this is an infinite loop iterator. You need to pay attention when handling in such cases.
Alternatively, you can also build an infinite loop iterator. The following example will loop indefinitely and return odd numbers because there are no stop conditions.
class InfIter:def __iter__(self):self.num = 1return selfdef __next__(self):num = self.numself.num += 2return num
Run the program:
>>> a = iter(InfIter())>>> next(a)1>>> next(a)3>>> next(a)5>>> next(a)7
The advantage of using iterator iterators is that they save resources. As shown above, you can get all odd numbers without storing on the entire digital system in memory.
Previous lesson: Operator overloading in Python
FAQ
What should I check before following these steps?
Confirm device and software compatibility, save important data, and make sure you have the required permissions, files, and account access.
Why might the process not work?
Common causes include outdated software, missing permissions, incompatible hardware, an unstable connection, or completing a step in the wrong order.
Can I undo the changes if necessary?
That depends on the tool or setting. Use built-in restore options when available, keep a backup, and record the original configuration first.
Reader Comments 0
Sign in with email or Google to join the discussion.