Categories: python

Iterable and Iterator in Python

What is an Iterable?

In Python, an iterable is an object that can be looped over, such as a list, tuple, or string. An iterator is an object that represents a stream of data, and it can be used to traverse through all the elements of an iterable. The built-in function iter() can be used to create an iterator from an iterable. Once an iterator is created, the built-in function next() can be used to retrieve the next element from the iterator. The iterator automatically raises a StopIteration exception when there are no more elements to return.

Note:

  • Every iterator is also an iterable, but not every iterable is an iterator in Python.
  • An iterable is an object that can be looped over, such as a list, tuple, set, dictionary, or string. These objects have an in-built dunder method called iter() which allows them to be iterated over. In other words, an iterable is something that can be used in a for loop and implement the protocol of iteration.
  • An iterator, on the other hand, is an object that represents a stream of data and it can be used to traverse through all the elements of an iterable. An iterator has the __next__() method, which returns the next item of the object. It also keeps the state of the iteration, which means it remembers where it is in the iteration. The built-in function iter() can be used to create an iterator from an iterable.
  • To make an object an iterator, it needs to define the __iter__() method, which returns an iterator, or a __getitem__ method with sequential indexes starting with 0.
  • Therefore, an iterable is something that can be iterated over, but an iterator is an object that does the actual iterating.
Example: Creating an Iterator from a list as follows:
my_list = [1, 2, 3, 4, 5]
my_iter = iter(my_list)

You can then use the next() function to retrieve the next element from the iterator.

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

You can also use a for loop to iterate over the elements of an iterator:

for element in my_iter:
    print(element)

This will output:

3
4
5

You can also use the __next__() method to retrieve the next element from the iterator

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

It’s important to note that once the iterator reaches the end of the iterable and there are no more elements to return, it will raise a StopIteration exception.

Example: Making a class Iterable by creating custom Iterator
class MyNumbers:
    def __init__(self, numbers):
        self.numbers = numbers
    
    def __iter__(self):
        return MyNumberIterator(self.numbers)

class MyNumberIterator:
    def __init__(self, numbers):
        self.numbers = numbers
        self.index = 0
    
    def __next__(self):
        if self.index >= len(self.numbers):
            raise StopIteration
        current = self.numbers[self.index]
        self.index += 1
        return current

In this example, the MyNumbers class has a __iter__() method that returns an instance of MyNumberIterator. The MyNumberIterator class has a __next__() method that returns the next element in the list of numbers and keeps track of the current index.

You can use a for loop to iterate over the elements of the MyNumbers class:

numbers = MyNumbers([1, 2, 3, 4, 5])
for number in numbers:
    print(number)

This will output:

1
2
3
4
5

It’s important to note that the __iter__() method should return a new iterator object every time it is called, otherwise, it will not work correctly if you try to iterate over the same object multiple times.

Note: also read about Python __name__ Variable

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago