Our Latest News

An introduction to iterators in python

An introduction to iterators in python

What is an iterator?

Before talking about python’s iterators, it is important to mention that in the ancient days of C, if you wanted to iterate over an array, you could only use a for loop

But this usually has a lot of problems, first of all, is inconsistent writing of different container types traversal, in addition is the loop condition is occasionally written wrong error, but also have to find a half-day bug, you know we just want to simply traverse a list ah, so painful?

Then our main character iterator came on the scene!

In python, for example, whether it is in the form of dictionaries, lists or tuples, you can use the for statement to get it done.

Why use iterators

So the problem that iterators help us solve is obvious, we don’t have to remember so many different ways to write iterable objects anymore, we just need one, which greatly allows us to focus more on writing bugs (not)

How to build an iterator

I believe that after reading the above you already know that the iterator is equivalent to the system of different iterable objects to help you make a unified interface, so what is behind the iterable object in the end?

Iteration, of course, does not need to list the boss himself to perform, but to send their own brother to perform, so who is this brother?

First you can use dir to see the methods and properties that our iterable object has.

It’s the iter method, which simply means that if it’s there, then it’s an iterable object.

So what does an iterable object do at this moment when it enters the for statement? It will return the iter method as an object and then call the next method, which is the real iterator that can get the list’s little brother, the iter method, through the iter method, so that it can call the next method directly.

Essentially if an object has iter and next methods then it must be an iterable object.

Below I’ve constructed an iterable object that can be output in reverse.

    GET A FREE QUOTE

    FPGA IC & FULL BOM LIST

    We'd love to

    hear from you

    Highlight multiple sections with this eye-catching call to action style.

      Contact Us

      Exhibition Bay South Squre, Fuhai Bao’an Shenzhen China

      • Sales@ebics.com
      • +86.755.27389663