Python Iterators | Stop Iteration | Stop once twenty iterations: | Create associate Iterator | Create associate Iterator


Python Iterators | StopIteration | Stop once twenty iterations: | Create associate Iterator | Create associate Iterator

Python Iterators

An iterator is associate object that contains a numerable range of values.

An iterator is associate object which will be iterated upon, which means that you just will traverse through all the values.

Technically, in Python, associate iterator is associate object that implements the iterator protocol, thataccommodates the ways __iter__() and __next__().

Iterator vs Iterable
Lists, tuples, dictionaries, and sets ar all iterable objects. they’re iterable containers that you’ll be able to get associate iterator from.

All these objects have a iter() technique that is employed to urge associate iterator:

Example

Return associate iterator from a tuple, and print every value:


mytuple = (“apple”, “banana”, “cherry”)
myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))

Run example »

Even strings ar iterable objects, and may come associate iterator:

Example
Strings also are iterable objects, containing a sequence of characters:

mystr = “banana”
myit = iter(mystr)

print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))

Looping Through associate Iterator

We can additionally use a for loop to retell through associate iterable object:

Example
Iterate the values of a tuple:

mytuple = (“apple”, “banana”, “cherry”)

for x in mytuple:
print(x)

Example
Iterate the characters of a string:

mystr = “banana”

for x in mystr:
print(x)

The for loop really creates associate iterator object and executes the next() technique for every loop


 

Create associate Iterator


To create associate object/class as associate iterator you’ve got to implement the ways __iter__() and __next__() to your object.

As you’ve got learned within the Python Classes/Objects chapter, all categories have a performreferred to as__init__(), thatpermitsyou are doing some initializing oncethe thing is being created.

The __iter__() technique acts similar, you’ll be able to do operations (initializing etc.), howevershouldcome the iterator object itself.

The __next__() techniqueadditionallypermits you to try and do operations, and shouldcomefollowing item within the sequence.

Example
Create associate iterator that returns numbers, beginning with oneand every sequence can increase by one (returning one,2,3,4,5 etc.):

class MyNumbers:
def __iter__(self):
self.a = 1
come self

def __next__(self):
x = self.a
self.a += 1
return x

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter)

StopIteration

The example on top of would continue forever if you had enough next() statements, or if it absolutely wasemployed in a for loop.

To prevent the iteration to travel on forever, we will use the StopIteration statement.

In the __next__() techniquewe will add a terminating condition to lifta mistake if the iteration is completed a nominativerange of times:

Example

Stop oncetwenty iterations:


class MyNumbers:
def __iter__(self):
self.a = 1
come self

def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration

myclass = MyNumbers()
myiter = iter(myclass)

for x in myiter:
print(x)

Python Iterators | StopIteration | Stop once twenty iterations: | Create associate Iterator | Create associate Iterator

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories