ConcepttheIteratorin python
theIteratorAn object that contains a specified number of values that are stored in order behind each other since when you want to access the values in it you can access its values one by one in the same order in which they are stored.
In fact, whenever you reach a value in it, you will be able to reach the next value placed immediately after it.
Information about the Iterator
theIteratorIn Python, an object that implements a protocol calledItator Protocol.
This protocol is implemented by calling the two equipped functions: __iter__()and__next__().
So you can create Iteratoryour own if you doOverridethese functions correctly in case you wanted to.
the difference betweentheIteratorAnd thetheIterablein python
When creating an objectlist, tuple, set,Or, dictyou create an object of its type Iterable, where you can access the value of any element in them directly by mentioning a numbertheIndexortheKeyof the element.
objecttheIteratorIt is not possible to access specific values in it, because as we said before you can access its values in the same order in which they are stored.
Every time you want to get the next value in it, you will have to call a function with its namenext().
This function is designed to give you the following value intheIteratorEvery time you call it.
If you reach the endtheIterator- that is, to the last value in it - and you called it, it will return the errorStopIteration .
The important difference betweentheIterableAnd thetheIteratoris that the latter cannot directly access a specific value in it.
dealing withtheIteratorin python
Initially, to get a copy of an object of its type as an Iterableobject of its typeIterator,We use a ready-made function in Python callediter().
In the following example we have created listand placed 3 values in it.
Then we created iteratorit, and then displayed the values in it one by one.
Example
# my_list contains 3 values, its name is list here we created
my_list = ("Banana", "Orange", "Apple")
# my_list we put the values of the iterator object here we have created
my_iterator = iter(my_list)
# three times and display what it returns each time next() here we called the function
# my_iterator Note that each time it returns the next value in the object
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
• We will get the following result when we run the fileTest.
Orange
Apple
pass on valuestheIteratorBy loop forin Python
In the following example we have created listand placed 3 values in it.
Then we used the loop forto display the values in it one by one.
first example
# my_list contains 3 values, its name is list here we created
my_list = ("Banana", "Orange", "Apple")
# Then it will display its value, val and then put it in the variable my_list here every cycle the next value will be fetched from the object
for val in my_list:
print(val)
• We will get the following result when we run the fileTest.
Orange
Apple
Technical information
What you need to know here is that the Python interpreter converts the loop forinto an object iteratorand on this basis the loop returns the next value for each cycle.
So the loop foryou're using to pass through the values of any Iterableis as follows.
for element in iterable: # iterable Here we write what we want to do with the values of
Actually, the Python interpreter internally handles the loop forlike this.
# iterable from the iterator creates
iter_obj = iter(iterable)
# Don't stop while then it creates a loop
while True:
# iterator and every cycle in this loop tries to fetch the next value in the . object
try:
element = next(iter_obj)
# The loop will stop running as soon as there is no new value in the iterator object.
except StopIteration:
break
note
You do not have to understand how the loop forworks very precisely at this stage, but it is preferable to know that to understand how the Python language works and increase your experience in dealing with it.
You will also understand the code we wrote now with ease in later lessons when you learn how to handle bugs using the two words tryandexcept.
In the following example, we pass through all the characters of the text and display them one by one using the loopfor.
second example
# Here we have defined a variable containing text, ie containing a string of characters string = 'Python' # Then it will be shown .string Every cycle in the loop a character from this text will be fetched and stored in the variable for c in string: print(c)
• We will get the following result when we run the fileTest.
y
t
h
o
n
note
Since the loop forreturns the next character in the text in each cycle, this means that the type stris also consideredIterable.
Examples of creating Iteratorin Python
In the following example, we construct a class that gives us Iteratoran infinity. Which we have builtInfinite Iterator.
first example
# __next__() and __iter__() for the Override functions because it does an Iterator that represents IterCounter here we created a class named class IterCounter: # is 0 IterCounter Here we said the first value that will be given to any object created from the class def __iter__(self): self.num = 0 return self # plus 1 num will be the value of the next() variable every time we call the IterCounter function here we said the next value that the object we create from the class will return def __next__(self): self.num += 1 return self.num # iter_counter and then we store it in the iter() object by the iterator function and convert it directly to IterCounter here we create an object from the class iter_counter = iter(IterCounter()) # next() every time we pass it to the iter_counter function here we have shown the next value that the object will return print(next(iter_counter)) print(next(iter_counter)) print(next(iter_counter)) print(next(iter_counter)) print(next(iter_counter))
• We will get the following result when we run the fileTest.
2
3
4
5
In the following example we have built a class that gives Iteratorus the multiples of 2 with the user being able to specify the maximum number of values to be returned.
second example
class PowerTwo: # A number can be passed to it directly when creating an object from this class's end property def __init__(self, end=1): self.end = end # is equal to 0 next() which we will use to calculate how many times the function n has been called here we have made the initial value of the variable def __iter__(self): self.n = 1 return self # The end value will be returned less than the value of the property n if the value of the variable ,next() here we said that whenever the function is called # which means that there is no longer any value in the StopIteration object for the next double, and if it is not smaller than it will return the error def __next__(self): if self.n <= self.end: result = 2 ** self.n self.n += 1 return result else: raise StopIteration # next() and then print the five multiples of 2 each time the end function is called and pass the value 5 in place of the PowTwo property. Here we created an object from the class for val in PowTwo(5): print(val)
• We will get the following result when we run the fileTest.
4
8
16
32