...

Web Technologies - PYTHON

Back to Course

Lesson Description


Lession - #282 Python Iterators



Iterators in Python

An iterator is a collection of values that may be counted.

An iterator is a type of object that can be iterated over, which means you can go over all of the values.

An iterator is a Python object that implements the iterator protocol, which includes the methods __iter__(>
and __next__ (>
.


Iterable vs. Iterator

Iterable objects include lists, tuples, dictionaries, and sets. They are iterable containers from which an iterator can be obtained.

The iter(>
method on all of these types is used to get an iterator:

Example
Return an iterator from a tuple, and print each value:

mytuple = ("apple", "mango", "orange">
myiterator = iter(mytuple>
print(next(myiterator>
>
print(next(myiterator>
>
print(next(myiterator>
>

Output:

Sorry cannot be displayed Try it here

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

mystr = "orange"
myitr = iter(mystr>
print(next(myitr>
>
print(next(myitr>
>
print(next(myitr>
>
print(next(myitr>
>
print(next(myitr>
>
print(next(myitr>
>

Output:

Sorry cannot be displayed Try it here


Construct an Iterator

You must implement the methods __iter__(>
and __next__(>
in your object/class to make it an iterator.

All classes have a function called __init__(>
, which allows you to do some initialising while the object is being formed, as you learned in the Python Classes/Objects chapter.

You can execute actions (initialising, etc.>
with the __iter__(>
method, but you must always return the iterator object itself.

You can also perform operations with the __next__(>
method, which must return the next item in the series.

class MyNumbers:
  def __iter__(self>
: self.b = 2 return self def __next__(self>
: x = self.b self.b += 2 return x myclass = MyNumbers(>
myiterator = iter(myclass>
print(next(myiterator>
>
print(next(myiterator>
>
print(next(myiterator>
>
print(next(myiterator>
>
print(next(myiterator>
>

Output:

Sorry cannot be displayed Try it here