Python Iterators

Iterators are an item that can be restored. In this exercise, you learn how employers and how to build your own _iter_next_ methods.


Table of Contents:

  • What are iterators in Python?
  • Iterating Through an Iterator in python 
  • How for loop actually works?
  • Building your own Iterator in Python 
  • Python Infinite Iterators

What are Iterators in Python?

Iterators are everywhere in Python. It is carried out in a soft, circular shape, grammar, generator, etc.
The Iterator of Python is a great item to restore. The product will restore the data, one at a time.
Technically, the Python product must run in two different ways, __ __iter () and ___ _______ (), together with the name of the rebate.
An item can be repeated if we can get it. Most Python refrigerators such as: lists, burglars, straps, etc.
The expression () (which returns the __ __iter () method returns to the schedule for them.

Iterating Through an Iterator in python:

We use the following () to hand them over through all cars. When you reach the end of the road there is no information to support, which will increase the suspension. Here is an example.

# define a list
my_list = [4, 7, 0, 3]

# get an iterator using iter()
my_iter = iter(my_list)

## iterate through it using next()

#prints 4
print(next(my_iter))

#prints 7
print(next(my_iter))

## next(obj) is same as obj.__next__()

#prints 0
print(my_iter.__next__())

#prints 3
print(my_iter.__next__())

## This will raise error, no items left

next(my_iter)

More than one of the confusion is using the directories. Using this, we can deal with all the items that the proposer can return, for example, list, letter, file, etc.

>>> for element in my_list:
...     print(element)
...     
4
7
0
3

How for loop actually works?

As you can see in the previous example, you can put it in a direct list.
In fact, the circle can put an end to something unusual. Let's look at the how loop treatment actually in Python.

# create an iterator object from that iterable
iter_obj = iter(iterable)

# infinite loop
while True:
    try:
        # get the next item
        element = next(iter_obj)
        # do something with element
    except StopIteration:
        # if StopIteration is raised, break from loop
        break

In fact, it was implemented as.
So inside, to create the object using the iterator, iter_obj by calling the iter
Intelligent, this circle is actually the limitations of a circle.
In the circle, call the next step () to go to the front of the body for a valuable orloop. After all the products outdoors, StopIteration has already carried out the completion of the circuit and the interior. Keep in mind that any other exceptions will happen.

Building your own Iterator in Python:

Building a project is easier than Python. We have to make __iter __ () and __next __ () a traditional way.
__Iter __ () Returns the Strategic Object itself. If necessary, it can be done several times.
The __next __ () method should return the article to the next sequence. Point out, and call the next phone, The quit should be raised.
Here, some examples have been shown to give us the next 2 rd. Electric power starts from zero to the number of users.

class PowTwo:
    """Class to implement an iterator
    of powers of two"""

    def __init__(self, max = 0):
        self.max = max

    def __iter__(self):
        self.n = 0
        return self

    def __next__(self):
        if self.n <= self.max:
            result = 2 ** self.n
            self.n += 1
            return result
        else:
            raise StopIteration 

Now we can do anonymous with them like this.

>>> a = PowTwo(4)
>>> i = iter(a)
>>> next(i)
1
>>> next(i)
2
>>> next(i)
4
>>> next(i)
8
>>> next(i)
16
>>> next(i)
Traceback (most recent call last):
...
StopIteration

We can also use the circle to be longer in the classroom.

>>> for i in PowTwo(5):
...     print(i)
...    
1
2
4
8
16
32

Python Infinite Iterators:

It is not necessary for the product to escape. We can not restrict people who have been upset (never ever). We should be careful when dealing with a strike.

>>> int()
0

>>> inf = iter(int,1)
>>> next(inf)
0
>>> next(inf)
0

This is a simple example of repeated bounds. The work of the buildings () can be called two arguments of the first debate should be a dependable and functional item. Calls for strategic activities are limited to the same cost.
I can see that the work INT () always returns 0. Because of the culture like Peter (INT, 1) Returns the iterator called INT () is limited to all value 1. Never happened and found iterator boundary. We can also build our attractive borders. At the bottom of the curve, in theory, all the numbers.

class InfIter:

    """Infinite iterator to return all
        odd numbers"""

    def __iter__(self):
        self.num = 1
        return self

    def __next__(self):
        num = self.num
        self.num += 2
        return num

Be careful about adding a stopping situation, when you return some of the different types of corners.

The advantage of using strategies is to store energy. As mentioned above, we can get all the fake numbers without saving all the memory numbers. We can have a good dimension (unimaginably) a memorable memory. The Iterator code also makes us look cool. There is an easy way to create iterators to pray.

To getting expect level training for Python training in your Location – Python training in Chennai | Python training institute in Chennai | Python Course institute in Chennai | Python training in Bangalore | Python training institute in Bangalore Python training in Electronic City Python training in Jaya Nagar | Python training in Pune | Python training institute in Pune | Python training in OMR | Python training in Velachery | Python training in Tambaram Python training in Annanagar | Python training in Marathahalli Python training in Btm | Python Online Training | Online Certification Course Python Course in Chennai Python interview questions and answers | Python tutorials | Python training in Indira Nagar | Python Course in Btm | Python Course in Marathahalli Python training institute in Marathahalli Python course institute in Btm Python course in Electronic City

Comments

Post a Comment

Popular posts from this blog

Python – Functions

What is Django in python?

Python Shallow Copy and Deep Copy