home PYTHONJAVA
 

Python3 Iterators and Builders


iterator

Iteration is one of Python's most powerful features and a way to access collection elements.

An iterator is an object that remembers the location of the traversal.

The iterator object is accessed from the first element of the collection until all elements have been accessed. The iterator can only go backwards without going forward.

There are two basic methods for iterators: iter() and next().

Strings, lists, or tuple objects can be used to create iterators:

Instance (Python 3.0+)

>>>list=[1 ,2,3 ,4] >>> it = Iter(list) # Create an iterator object >>> print ( next(it)) # Output the next element of the iterator 1 >>> print ( next(it)) 2 >>>

Iterator objects can be traversed using the regular for statement:

Instance (Python 3.0+)

#!/usr/bin/python3 list=[1,2,3,4 ] it = iter(list) # Create an iterator object for x in it: print (x, end=" ")

Execute the above program, the output is as follows:

1 2 3 4

Can also be used next() function:

Instance(Python 3.0+)

#!/usr/bin/python3 import sys # Introduce sys Module

You can also use the next() function:

Instance(Python 3.0+)

#!/usr/bin/python3 import sys # Introducing the sys module list=[1,2,3,4] it = iter(list) # Create an iterator object while True: try: print (next(it)) except StopIteration: sys.exit()

Execute the above program, the output is as follows:

1
2
3
4

Create an iterator

Using a class as an iterator requires implementing two methods __iter__() and __next__() in the class.

If you already know about object-oriented programming, you know that classes have a constructor, and Python's constructor is __init__(), which is executed when the object is initialized.

The

__iter__() method returns a special iterator object that implements the __next__() method and identifies the completion of the iteration through the StopIteration exception.

The

__next__() method (next() in Python 2) returns the next iterator object.

Create an iterator that returns a number with an initial value of 1 and incrementing by 1:

Instance(Python 3.0+)

class MyNumbers: def __iter__(self): self.a = 1 return 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))

Execution output is:

1
2
3
4
5

StopIteration

The StopIteration exception is used to identify the completion of an iteration to prevent an infinite loop. In the __next__() method we can set the StopIteration exception to be fired after the specified number of loops has been completed.

Stop execution after 20 iterations:

Instance(Python 3.0+)

class MyNumbers: def __iter__(self): self.a = 1 return 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)

Execution output is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Builder

In Python, a function that uses yield is called a generator.

Unlike normal functions, the generator is a function that returns an iterator. It can only be used for iterative operations. It is easier to understand that the generator is an iterator.

When the call generator runs, the function pauses and saves all current run information each time it encounters yield, returns the value of yield, and continues to run from the current position the next time the next() method is executed.

Invoke a generator function that returns an iterator object.

The following example uses yield to implement the Fibonacci sequence:

Instance(Python 3.0+)

#!/usr/bin/python3 import sys def fibonacci(n): # Generator function - Fibonacci a, b, counter = 0, 1, 0 while True: if (counter > n): return yield a a, b = b, a + b counter += 1 f = fibonacci(10) # f Is an iterator that is generated by the generator while True: try: print (next(f), end=" ") except StopIteration: sys.exit()

Execute the above program, the output is as follows:

0 1 1 2 3 5 8 13 21 34 55





welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.