create account

Python Iterators and Tricks By albro by albro

View this thread on: hive.blogpeakd.comecency.com
· @albro ·
$2.93
Python Iterators and Tricks By albro
<center>![Python Iterators and Tricks](https://files.peakd.com/file/peakd-hive/albro/EoiTEvYapeiZiNL8t6J3aEkSrArQQKhdkYAxV59K1PQafTAy4e6RJTUmgwFPp2uxM6y.jpg)</center>

<p><strong>Iterator</strong>s have many uses in <i>programming languages</i>. Programmers frequently use iterators when using ready-made data structures. In simpler words, with <strong>iterator</strong>s, we can traverse a <a href="https://peakd.com/hive-169321/@albro/python-list-and-tricks-by-albro">list</a>, array, or other specific data structure and check each of its elements in a <a href="https://peakd.com/hive-169321/@albro/python-loops-and-tricks-by-albro">loop</a>.</p>
<h3>What is an iterator?</h3>
<p>Maybe understanding the concept of <i>iterator</i> is a bit difficult and confusing!</p>
<p>Let's see the concept and situation of using iterators with a very simple example in the Python programming language.</p>
<p>Suppose you have a <a href="https://peakd.com/hive-169321/@albro/python-list-and-tricks-by-albro">list</a> of some numbers and you want to traverse on this list. As you know, this is possible simply by using a <a href="https://peakd.com/hive-169321/@albro/python-loops-and-tricks-by-albro">for loop</a>.</p>
<pre><code>my_list = [1, 2, 3, 4]<br />
for x in my_list:
    print(x) #or do something ...</code></pre>
<p><strong>But what happens behind the performance of the above loop?</strong></p>
<p>In a very simple case, suppose we have a pointer <a href="https://peakd.com/hive-169321/@albro/python-variable-and-constant-by-albro">variable</a> to the first element of this list (in the <a href="https://peakd.com/hive-169321/@albro/python-list-and-tricks-by-albro">Python list data structure</a>). When we use the list in a <code>for</code> loop, in the first execution of the loop, the first element is checked and traversed.</p>
<p>In the second iteration of <a href="https://peakd.com/hive-169321/@albro/python-loops-and-tricks-by-albro">the loop</a>, we must move one element forward, that is, our pointer must point to the second element (the element after the current element).</p>
<p>The said process is repeated for the number of elements in the list so that we don't have any more elements to replace with the previous element; In this case, our loop is completed. simply!</p>
<p>The concept of iterator in an object is as simple as it was said!!</p>
<p>In the picture below, the general and sequential process of iterators is drawn.</p>

<center>![What is python Iterators](https://files.peakd.com/file/peakd-hive/albro/Eo8SHaZJXrWjccJ8zbas1mcBNcttyBY2zmCJwtfpZW6e8fRp98XAZnt1kYDZRu9MKxN.jpg)</center>

<p>When we are creating an arbitrary data structure in Python, if we want our data structure to have the feature of being iterated, we must implement two methods related to iterators in our <a href="https://peakd.com/hive-169321/@albro/python-calss-by-albro">class</a>.</p>
<p><strong><code>__iter__</code> function</strong></p>
<p>This function is called when an object of our data structure is placed in a location for navigation. (for example in the <code>for</code> loop)</p>
<p>The <code>__iter__</code> method actually returns an object that has a method named <code>__next__</code>.</p>
<p><strong><code>__next__</code> function</strong></p>
<p>In the <code>__next__</code> method, a process is performed that the navigation pointer of our elements moves one step forward, points to the next element and finally outputs the current element.</p>
<h3>An example to understand the structure of iterators in Python</h3>
<p>To better understand the structure of iterators, suppose we have a <a href="https://peakd.com/hive-169321/@albro/python-calss-by-albro">class</a> with a <a href="https://peakd.com/hive-169321/@albro/python-variable-and-constant-by-albro">variable</a> named <code>current</code> and set its initial value to <code>1</code>.</p>
<pre><code>class Numbers:
    def __init__(self):
        self.current = 1</code></pre>
<p>Now, if we create an example from our test class and try to use it in a simple <a href="https://peakd.com/hive-169321/@albro/python-loops-and-tricks-by-albro">for loop</a>, we will encounter an error!</p>
<pre><code>obj = Numbers()<br />
for x in obj:
      print(x)<br /><br />
# Run Result:
# Traceback (most recent call last):
#   File "<pyshell#7>", line 1, in <module>
#     for x in obj:
# TypeError: 'Numbers' object is not iterable</code></pre>
<p>As it is clear from the last line of the given error, the objects of the <code>Numbers</code> class cannot be iterated, or in other words, they're not iterable.</p>
<p>
As mentioned before, we need two more helper functions to make the desired class iterable. Next, we will add two necessary methods to our class. That is, our class will be something like the code below.</p>
<pre><code>class Numbers:
    def __init__(self):
        self.current = 1<br />
    def __iter__(self):
        return self<br />
    def __next__(self): #have infinit end!
        output = self.current
        self.current += 1
        return output</code></pre>
<p>Now, if we run the same loop as before, we will see the number 1 printed in the output at the beginning, and the number 2 in the next line, and this process continues to infinity.</p>
<p>Usually, there is a certain limitation in the data structure we have; For example, there is a countable number of elements in it, or in our educational example (<code>Numbers</code> class), it can be considered that the iteration will advance to a certain ceiling.</p>
<p>In order to take the expected ceiling as input, we change the constructor of the class and we will take the two values <code>low</code> and <code>high</code> as input when creating the object.</p>
<p>Also, to control the non-overflow of the expected limit, a condition should be placed in the <code>__next__</code> method to check that the expected limit has been reached. If we reach our ceiling, we can use the <code>StopIteration</code> statement to announce to the <code>for</code> loop that the iteration is over.</p>
<pre><code>class Numbers:
    def __init__(self, low, high):
        self.current = low
        self.limit = high<br />
    def __iter__(self):
        return self<br />
    def __next__(self):
        if self.current > self.limit:
            raise StopIteration
        output = self.current
        self.current += 1
        return output</code></pre>
<p>As a result of executing the following test code, we will have the numbers 1 to 10 in the output.</p>
<pre><code>obj = Numbers(1, 10)<br />
for x in obj:
    print(x)</code></pre>
<p>Now if we use the same object <code>obj</code> in another loop, you will see that no result will be obtained!</p>
<p>The reason for this is that the variable related to <code>current</code> has reached its maximum once the iteration operation has been executed, and in other times the iteration, because it has reached the <code>limit</code>, terminates the loop at the beginning of the execution by declaring <code>StopIteration</code>.</p>
<p>To avoid this, we can return the variables used as pointers (iterations) to their initial value in the <code>__iter__</code> method.</p>
<p>Here only the value of the <code>current</code> variable changes and our problem is exactly this variable.</p>
<p>The problem can be easily solved by keeping the <code>low</code> value when creating an object from the class and assigning it to the <code>current</code> variable when executing the <code>__iter__</code> method.</p>
<pre><code>class Numbers:
    def __init__(self, low, high):
        self.low = low
        self.limit = high<br />
    def __iter__(self):
        self.current = self.low
        return self<br />
    def __next__(self):
        if self.current > self.limit:
            raise StopIteration
        output = self.current
        self.current += 1
        return output</code></pre>
<p>Sometimes, due to the complexity of the process of maintaining the current element and jumping to its next element in each iteration step, the <code>iterable</code> class is defined as a separate class and only the <code>__iter__</code> method is used in the main class.</p>
<p>If <code>__iter__</code> is called, an object of the auxiliary class is created and returned; It should be noted that the auxiliary class must have two functions <code>__iter__</code> and <code>__next__</code>.</p>
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 156 others
properties (23)
authoralbro
permlinkpython-iterators-and-tricks-by-albro
categoryhive-169321
json_metadata{"app":"peakd/2023.5.1","format":"markdown","author":"albro","tags":["development","programming","gosh","threads","neoxag","chessbrothers","python","iterators","leofinance"],"users":["albro"],"image":["https://files.peakd.com/file/peakd-hive/albro/EoiTEvYapeiZiNL8t6J3aEkSrArQQKhdkYAxV59K1PQafTAy4e6RJTUmgwFPp2uxM6y.jpg","https://files.peakd.com/file/peakd-hive/albro/Eo8SHaZJXrWjccJ8zbas1mcBNcttyBY2zmCJwtfpZW6e8fRp98XAZnt1kYDZRu9MKxN.jpg"]}
created2023-06-01 16:38:00
last_update2023-06-01 16:38:00
depth0
children4
last_payout2023-06-08 16:38:00
cashout_time1969-12-31 23:59:59
total_payout_value1.468 HBD
curator_payout_value1.464 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length8,376
author_reputation26,777,723,117,730
root_title"Python Iterators and Tricks By albro"
beneficiaries
0.
accounthive-169321
weight200
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id124,070,048
net_rshares6,750,687,265,994
author_curate_reward""
vote details (220)
@chessbrotherspro ·
<h3>Congratulations!</h3><hr /><div class="pull-right"><img src="https://files.peakd.com/file/peakd-hive/chessbrotherspro/AJoJKGVARKHFCTHG7ee3GNkn5RMN7wixeJ52ipAgzDZ4QmeTcBdsk8hpi4pgj4e.png" alt="You have obtained a vote from CHESS BROTHERS PROJECT"/></div><div class="text-justify"><h3>✅ Good job. Your post has been appreciated and has received support from <a href="/@chessbrotherspro"><b>CHESS BROTHERS</b></a> ♔ 💪</h3><p><br>♟ We invite you to use our hashtag <b>#chessbrothers</b> and learn more <a href="/@chessbrotherspro/introducing-chess-brothers-project-the-most-innovative-community-combining-chess-fitness-and-more"><b>about us</b></a>.</p><p>♟♟ You can also reach us on our <a href="https://discord.gg/73sK9ZTGqJ" rel="noopener" title="This is going to take you to the Discord of Chess Brothers"><b>Discord server</b></a>  and promote your posts there. </p><p>♟♟♟  Consider <a href="/@chessbrotherspro/teamwork-is-worthwhile-join-the-chess-brothers-healing-trail-supporting-the-work-being-done-and-earning-rewards"><b>joining our curation trail</b></a> so we work as a team and you get rewards automatically.</p><p>♞♟ Check out our <a href="/@chessbrotherspro"><b>@chessbrotherspro</b></a> account to learn about the curation process carried out daily by our team.</p><br>🥇 If you want to earn profits with your HP delegation and support our project, we invite you to join the <i>Master Investor</i> plan. <a href="/@chessbrotherspro/master-investor-plan-or-programa">Here you can learn how to do it.</a></div><div class="text-center"><p><br>Kindly</p><p><strong><em>The CHESS BROTHERS team</em></strong></p></div>
properties (22)
authorchessbrotherspro
permlinkre-python-iterators-and-tricks-by-albro-20230602t031019z
categoryhive-169321
json_metadata"{"app": "beem/0.24.26"}"
created2023-06-02 03:14:00
last_update2023-06-02 03:14:00
depth1
children0
last_payout2023-06-09 03:14:00
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,628
author_reputation56,110,874,488,960
root_title"Python Iterators and Tricks By albro"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id124,085,221
net_rshares0
@ecency ·
**Yay!** 🤗<br>Your content has been **boosted with Ecency Points**, by @albro. <br>Use Ecency daily to boost your growth on platform! <br><br><b>Support Ecency</b><br>[Vote for new Proposal](https://hivesigner.com/sign/update-proposal-votes?proposal_ids=%5B245%5D&approve=true)<br>[Delegate HP and earn more](https://ecency.com/hive-125125/@ecency/daily-100-curation-rewards)
properties (22)
authorecency
permlinkre-202362t121957954z
categoryhive-169321
json_metadata{"tags":["ecency"],"app":"ecency/3.0.20-welcome","format":"markdown+html"}
created2023-06-02 12:19:57
last_update2023-06-02 12:19:57
depth1
children0
last_payout2023-06-09 12:19:57
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length375
author_reputation549,971,524,037,747
root_title"Python Iterators and Tricks By albro"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id124,093,833
net_rshares0
@poshthreads ·
https://leofinance.io/threads/albro/re-leothreads-35f3wbejh
<sub> The rewards earned on this comment will go directly to the people ( albro ) sharing the post on LeoThreads,LikeTu,dBuzz.</sub>
properties (22)
authorposhthreads
permlinkre-albro-python-iterators-and-tricks-by-albro12578
categoryhive-169321
json_metadata"{"app":"Poshtoken 0.0.2","payoutToUser":["albro"]}"
created2023-06-01 19:14:42
last_update2023-06-01 19:14:42
depth1
children0
last_payout2023-06-08 19:14:42
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length193
author_reputation415,452,450,635,513
root_title"Python Iterators and Tricks By albro"
beneficiaries
0.
accountnomnomnomnom
weight10,000
max_accepted_payout1,000,000.000 HBD
percent_hbd0
post_id124,074,417
net_rshares0
@stemsocial ·
re-albro-python-iterators-and-tricks-by-albro-20230602t032146588z
<div class='text-justify'> <div class='pull-left'>
 <img src='https://stem.openhive.network/images/stemsocialsupport7.png'> </div>

Thanks for your contribution to the <a href='/trending/hive-196387'>STEMsocial community</a>. Feel free to join us on <a href='https://discord.gg/9c7pKVD'>discord</a> to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support.&nbsp;<br />&nbsp;<br />
</div>
properties (22)
authorstemsocial
permlinkre-albro-python-iterators-and-tricks-by-albro-20230602t032146588z
categoryhive-169321
json_metadata{"app":"STEMsocial"}
created2023-06-02 03:21:45
last_update2023-06-02 03:21:45
depth1
children0
last_payout2023-06-09 03:21:45
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length565
author_reputation22,460,334,324,555
root_title"Python Iterators and Tricks By albro"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id124,085,343
net_rshares0