avatarDr. Soumen Atta, Ph.D.

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2808

Abstract

="188a">Iterators have a <code>next</code> method that provides the next element in the sequence. When no more elements are left, it raises the <code>StopIteration</code> exception.</p><div id="d1e6"><pre>my_list = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>] my_iter = <span class="hljs-built_in">iter</span>(my_list)

<span class="hljs-built_in">print</span>(my_iter.next()) <span class="hljs-comment"># Output: 1</span> <span class="hljs-built_in">print</span>(my_iter.next()) <span class="hljs-comment"># Output: 2</span> <span class="hljs-built_in">print</span>(my_iter.next()) <span class="hljs-comment"># Output: 3</span></pre></div><h1 id="fefd">4. Using Iterators and Iterables in Loops</h1><p id="0272">Python’s <code>for</code> loop is designed to work seamlessly with iterables. When looping, it internally handles creating an iterator and advancing through the elements.</p><div id="e0d5"><pre>my_list = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>] <span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> my_list: <span class="hljs-built_in">print</span>(item) <span class="hljs-comment"># Output: 1 2 3</span></pre></div><h1 id="3da1">5. Creating Custom Iterables and Iterators</h1><p id="b494">You can create your own custom iterables and iterators by implementing the <code>iter</code> and <code>next</code> methods.</p><div id="5912"><pre><span class="hljs-keyword">class</span> <span class="hljs-title class_">PowerOfTwo</span>: <span class="hljs-keyword">def</span> <span class="hljs-title function_">init</span>(<span class="hljs-params">self, max_power</span>): self.max_power = max_power self.current_power = <span class="hljs-number">0</span>

<span class="hljs-keyword">def</span> <span class="hljs-title function_">__iter__</span>(<span class="hljs-params">self</span>):
    <span class="hljs-keyword">return</span> self

<span class="hljs-keyword">def</span> <span class="hljs-title function_">__next__</span>(<span class="hljs-params">self</span>):
    <span class="hljs-keyword">if</span> self.current_power &lt;= self.max_power:
        result = <span class="hljs-number">2</span> ** self.current_power
        self.current_power += <span class="hljs-number">1</span>
        <span class="hljs-keyword">return</span> result
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">raise</span> StopIteration

powers = PowerOfTwo(<span class="hljs-number">4</span>) <span class="hljs-keyword">for</span> val <span class="hljs-keyword">in</span> powers: <span class="hljs-built_in">print</span>(val) <s

Options

pan class="hljs-comment"># Output: 1 2 4 8 16</span></pre></div><h1 id="9034">6. Conclusion</h1><p id="7b4d">In this tutorial, you’ve learned about the fundamental concepts of iterators and iterables in Python. Iterables are objects that can be looped over, while iterators are objects that maintain the state of the iteration. You’ve seen how to create and use both built-in and custom iterables and iterators to traverse data efficiently.</p><p id="6913">By mastering iterators and iterables, you’ll be able to take full advantage of Python’s looping capabilities and create more efficient and expressive code. These concepts are crucial for effective data manipulation, and they underlie many Python programming paradigms.</p><div id="9cfc" class="link-block"> <a href="https://soumenatta.medium.com/membership"> <div> <div> <h2>Join Medium with my referral link - Dr. Soumen Atta, Ph.D.</h2> <div><h3>As a Medium member, a portion of your membership fee goes to writers you read, and you get full access to every story…</h3></div> <div><p>soumenatta.medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*l4Z-1XK8tFHaaAW8)"></div> </div> </div> </a> </div><div id="afe7" class="link-block"> <a href="https://levelup.gitconnected.com/python-generators-unlocking-the-power-of-iterators-c0f593b37bb5"> <div> <div> <h2>Python Generators: Unlocking the Power of Iterators</h2> <div><h3>Python generators are a powerful tool that allows you to create iterators in a simple and efficient manner. Generators…</h3></div> <div><p>levelup.gitconnected.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*0NqAAVQivXoh_jLmSJxGzA.png)"></div> </div> </div> </a> </div><div id="cde8" class="link-block"> <a href="https://blog.devgenius.io/python-generators-a-complete-guide-8f0a561616ef"> <div> <div> <h2>Python Generators: A Complete Guide</h2> <div><h3>Python generators are a powerful tool for creating iterators that can generate values on the fly. Generators allow you…</h3></div> <div><p>blog.devgenius.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*N0lgfhm1h3fKuVRn)"></div> </div> </div> </a> </div></article></body>

Python Iterators and Iterables Explained with Code Examples

Iterators and iterables are fundamental concepts in Python that facilitate efficient looping and data traversal. This tutorial will provide you with a clear understanding of iterators and iterables, along with code examples to demonstrate their usage.

Table of Contents

  1. Introduction to Iterators and Iterables
  2. Iterables: Objects with __iter__ Method
  3. Iterators: Objects with __next__ Method
  4. Using Iterators and Iterables in Loops
  5. Creating Custom Iterables and Iterators
  6. Conclusion

1. Introduction to Iterators and Iterables

  • Iterables: Objects that can be looped over or iterated upon. Lists, tuples, strings, dictionaries, and more are examples of iterables.
  • Iterators: Objects that allow you to iterate through an iterable’s elements. They maintain the state of the iteration.

2. Iterables: Objects with __iter__ Method

Iterables have an __iter__ method, which returns an iterator object. The iterator object is used to traverse the elements.

my_list = [1, 2, 3]
my_iter = my_list.__iter__()  # Equivalent to iter(my_list)

print(next(my_iter))  # Output: 1
print(next(my_iter))  # Output: 2
print(next(my_iter))  # Output: 3

3. Iterators: Objects with __next__ Method

Iterators have a __next__ method that provides the next element in the sequence. When no more elements are left, it raises the StopIteration exception.

my_list = [1, 2, 3]
my_iter = iter(my_list)

print(my_iter.__next__())  # Output: 1
print(my_iter.__next__())  # Output: 2
print(my_iter.__next__())  # Output: 3

4. Using Iterators and Iterables in Loops

Python’s for loop is designed to work seamlessly with iterables. When looping, it internally handles creating an iterator and advancing through the elements.

my_list = [1, 2, 3]
for item in my_list:
    print(item)  # Output: 1 2 3

5. Creating Custom Iterables and Iterators

You can create your own custom iterables and iterators by implementing the __iter__ and __next__ methods.

class PowerOfTwo:
    def __init__(self, max_power):
        self.max_power = max_power
        self.current_power = 0
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.current_power <= self.max_power:
            result = 2 ** self.current_power
            self.current_power += 1
            return result
        else:
            raise StopIteration

powers = PowerOfTwo(4)
for val in powers:
    print(val)  # Output: 1 2 4 8 16

6. Conclusion

In this tutorial, you’ve learned about the fundamental concepts of iterators and iterables in Python. Iterables are objects that can be looped over, while iterators are objects that maintain the state of the iteration. You’ve seen how to create and use both built-in and custom iterables and iterators to traverse data efficiently.

By mastering iterators and iterables, you’ll be able to take full advantage of Python’s looping capabilities and create more efficient and expressive code. These concepts are crucial for effective data manipulation, and they underlie many Python programming paradigms.

Python
Iterators
Iterables
Tutorial
Programming
Recommended from ReadMedium