My Coding > Programming language > Python > Python Iterator

Python Iterator

Python Iterator

Python can iterate trough many different data objects, which are iterable:


lst = [1,2,3,4]
dic = {'w1': 'one', 'w2': 'two', 'w3': 'three'}
str = "string"
val = 8
for i in lst: print(i, end=' ') # 1 2 3 4
for i in dic: print(i, end=' ') # w1 w2 w3
for i in str: print(i, end=' ') # s t r i n g
for i in val: print(i, end=' ') # TypeError: 'int' object is not iterable

Iterable objects in Python have object iterator, which points to next elements or raise an error StopIteration if objects are finished. To call iterator directly, you need to use function iter()

So you can rewrite this cycle with iterator, for example for dic:


it = iter(dic)
while True:
    try:
        I = next(it)
        print(i, end=' ')
    except StopIteration:
        break

It is more complicated, but it is explaining how this works in Python. Function next() call predefined function__next__() if it is exists. Now we can define or redefine our own __next__() function!


from random import random 
class RandomIterator:
    def __init__(self, k):   #initiate random sequence
        self.k = k              # number of random element
        self.i = 0              # counter
    def __iter__(self):      # method iter
        return self             # return intself
    def __next__(self):      # method next
        if self.i < self.k:     # check that we can calculater next object
            self.i += 1         # increade counter
            return random()     # fetch next object
        else:
            raise StopIteration # raise an error at the end of iterations

for x in  RandomIterator(3): print(x)
   #  0.7976183493606193
   #  0.002919405699900457
   #  0.6408160157614484

yield for short writing

We can use special generator yield() to make shorter writing


from random import random 
def random_generator(k):
    for i in range(k):
        yield random()

gen=random_generator(3)
for i in gen:
    print(i)
 # 0.7074683969601196
 # 0.2222520326598939
 # 0.23386693884925625

More tools for itertions in Python

More tools for iterations in Pyton you can find in modeile itertools use: import itertools


Published: 2021-09-25 07:07:58
Updated: 2021-09-25 07:23:37

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.