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

What is object oriented design patterns

A design pattern is a reusable solution to a commonly occurring problem in software design. They…

4 months ago

Factory Method Design Pattern in OODP

Factory Method is a creational design pattern that deals with the object creation. It separates…

4 months ago

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

10 months ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

10 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

10 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

11 months ago