How to create Python Iterable class ? - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we are going to see how to create an Iterable class in Python.
An iterator is an object that can be iterated through all the values in the object. In python Lists, tuples, dictionaries, and sets are all iterable objects, these are all can be iterate over the values.
The iter() is a method used to get the iterator from List, tuple, dictionary and set objects, through which the items are get iterated.
By default, all python classes are not iterable so that we can not traverse/iterate the values of the python class.  To make a class as iterable, you have to implement the __iter__() and __next__() methods in that class.
The __iter__() method allows us to make operations on the items or initializing the items and returns an iterator object.
The __next__() method allows us to do operations and it should return the next value of the sequence.
To make the example as simple, I am taking a simple use-case – Creating a class that allows iterating over a range of provided dates, and it always produces one day at a time on every loop.
from datetime import timedelta, date

class DateIterable:

    def __init__(self, start_date, end_date):
        # initilizing the start and end dates
        self.start_date = start_date
        self.end_date = end_date
        self._present_day = start_date

    def __iter__(self):
        #returning __iter__ object
        return self

    def __next__(self):
        #comparing present_day with end_date,
        #if present_day greater then end_date stoping the iteration
        if self._present_day >= self.end_date:
            raise StopIteration
        today = self._present_day
        self._present_day += timedelta(days=1)
        return today


if __name__ == '__main__':
    for day in DateIterable(date(2020, 1, 1), date(2020, 1, 6)):
        print(day)
Output:
2020-01-01
2020-01-02
2020-01-03
2020-01-04
2020-01-05
The above example iterates the days between the start and end days. The for loop creates an iterator object and executes the next() method for each loop, that’s why we see them each day in a separate line.
Note: StopItertion is used to prevent the iteration, usually, we prevent the iteration on a specific condition.
Python Iterators

How to Iterate Python Dictionary ?
How to Convert Python List Of Objects to CSV File
How to read JSON file in Python ?
How to Create or Delete Directories in Python ?
Python Set Data Structure in Depth
Convert any Number to Python Binary Number
Python – How to create Zip File in Python ?
How to Convert Iterable to Stream Java 8
Python – Find the biggest of 2 given numbers
How to Remove Spaces from String in Python
How to get Words Count in Python from a File
How to get Characters Count in Python from a File
How to merge two lists in Python
How to Read CSV File in Python
What are the different ways to Sort Objects in Python ?

How to Iterate Python Dictionary ?
How to Convert Python List Of Objects to CSV File
How to read JSON file in Python ?
How to Create or Delete Directories in Python ?
Python Set Data Structure in Depth
Convert any Number to Python Binary Number
Python – How to create Zip File in Python ?
How to Convert Iterable to Stream Java 8
Python – Find the biggest of 2 given numbers
How to Remove Spaces from String in Python
How to get Words Count in Python from a File
How to get Characters Count in Python from a File
How to merge two lists in Python
How to Read CSV File in Python
What are the different ways to Sort Objects in Python ?
 


Δ
 Python – Introduction
 Python – Features
 Python – Install on Windows
 Python – Modes of Program
 Python – Number System
 Python – Identifiers
 Python – Operators
 Python – Ternary Operator
 Python – Command Line Arguments
 Python – Keywords
 Python – Data Types
 Python – Upgrade Python PIP
 Python – Virtual Environment
 Pyhton – Type Casting
 Python – String to Int
 Python – Conditional Statements
 Python – if statement
 Python – *args and **kwargs
 Python – Date Formatting
 Python – Read input from keyboard
 Python – raw_input
 Python – List In Depth
 Python – List Comprehension
 Python – Set in Depth
 Python – Dictionary in Depth
 Python – Tuple in Depth
 Python – Stack Datastructure
 Python – Classes and Objects
 Python – Constructors
 Python – Object Introspection
 Python – Inheritance
 Python – Decorators
 Python – Serialization with Pickle
 Python – Exceptions Handling
 Python – User defined Exceptions
 Python – Multiprocessing
 Python – Default function parameters
 Python – Lambdas Functions
 Python – NumPy Library
 Python – MySQL Connector
 Python – MySQL Create Database
 Python – MySQL Read Data
 Python – MySQL Insert Data
 Python – MySQL Update Records
 Python – MySQL Delete Records
 Python – String Case Conversion
 Howto – Find biggest of 2 numbers
 Howto – Remove duplicates from List
 Howto – Convert any Number to Binary
 Howto  – Merge two Lists
 Howto – Merge two dicts
 Howto – Get Characters Count in a File
 Howto – Get Words Count in a File
 Howto – Remove Spaces from String
 Howto –  Read Env variables
 Howto – Read a text File
 Howto – Read a JSON File
 Howto –  Read Config.ini files
 Howto – Iterate Dictionary
 Howto – Convert List Of Objects to CSV
 Howto – Merge two dict in Python
 Howto – create Zip File
 Howto – Get OS info
 Howto – Get size of Directory
 Howto – Check whether a file exists
 Howto –  Remove key from dictionary
 Howto – Sort Objects
 Howto – Create or Delete Directories
 Howto – Read CSV File
 Howto – Create Python Iterable class
 Howto – Access for loop index
 Howto – Clear all elements from List
 Howto – Remove empty lists from a List
 Howto – Remove special characters from String
 Howto – Sort dictionary by key
 Howto – Filter a list