Monday 4 March 2019

Iterators in Python

Iterator in python is any python type that can be used with a ‘for in loop’. Python lists, tuples, dicts and sets are all examples of inbuilt iterators. These types are iterators because they implement following methods. In fact, any object that wants to be an iterator must implement following methods.

1.__iter__ method that is called on initialization of an iterator. This should return an object that has a next or __next__ (in Python 3) method.
2.next ( __next__ in Python 3) The iterator next method should return the next value for the iterable. When an iterator is used with a ‘for in’ loop, the for loop implicitly calls next() on the iterator object. This method should raise a StopIteration to signal the end of the iteration.

Below is a simple Python program that creates iterator type that iterates from 10 to given limit. For example, if limit is 15, then it prints 10 11 12 13 14 15. And if limit is 5, then it prints nothing.

# A simple Python program to demonstrate
# working of iterators using an example type
# that iterates from 10 to given value
# An iterable user defined type
class Test:
# Cosntructor
def __init__(self, limit):
self.limit = limit
# Called when iteration is initialized
def __iter__(self):
self.x = 10
return self
# To move to next element. In Python 3,
# we should replace next with __next__
def next(self):
# Store current value of x
x = self.x
# Stop iteration if limit is reached
if x > self.limit:
raise StopIteration
# Else increment and return old value
self.x = x + 1;
return x
# Prints numbers from 10 to 15
for i in Test(15):
print(i)
# Prints nothing
for i in Test(5):
print(i)

Output:
10
11
12
13
14
15

0 Comments:

Post a Comment

Popular Posts

Categories

AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (114) C (77) C# (12) C++ (82) Course (60) Coursera (176) coursewra (1) Cybersecurity (22) data management (11) Data Science (89) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (5) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (3) Pandas (3) PHP (20) Projects (29) Python (745) Python Coding Challenge (198) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses