Iteration | Iter | Iterators | Iterables — in Python

Ivjot Singh
The Startup
Published in
3 min readAug 3, 2020

Quite Confusing Right?

Let’s understand each term as it comes.

Iteration

Traversing over an object in python.
example:
let say we have a list as:

random_list = [4, 7, 9]

for element in random_list:
….print(element)

The above statements represents process of iteration, in which every element in the list is traversed and printed.

Iter

iter() is an inbuilt method in python which converts a python object to an iterator.

Iterator

Any python object which can be iterated over, ie. you can traverse upon all the values of the object.

or

An iterator is an object with a state it remembers where it is during iteration
and knows how to get the next value using __next__() method

Note: Iterator object returns one value at a time.

A Python iterator object must implement two special methods,
1: __iter__()
2: __next__()
collectively called the iterator protocol.

Traversing an iterator

random_list = [4, 7, 9]

# converting the above list

random_iterator = iter(random_list)

Now __next__ special method can be used to traverse on every element of the iterator but one by one.

print(next(random_iterator))
output: 4

print(next(random_iterator))
output: 7

print(next(random_iterator))
output: 9

print(next(random_iterator))
# error (Stop Iteration), as no items left

Iterating using next function manually

Better way of iterating over iterator:

Iterating using infinite while loop which breaks when no element left
Output

Fun Fact: Actual for loops in python which you apply on list, tuples etc (which are iterables) are implemented as above.

Iterables

Lists, tuples, dictionaries, and sets are all default iterable objects or containers ie. you can loop over them!

Note — An object is called iterable if we can get an iterator from it.

Identification:

Since everything in a python is a object
Any object that is a iterable will have __iter__() method in it which will return an iterator object.

That means, not only list tuples etc are iterators, you can actually create any class a iterable, ie. you can implement for loop in any object of any user defined class provided, it must have/override __iter__ method which returns iterator object.

For eg:

Let say I have a Developer class which contains 2 lists of python and javascript developers.

Trying looping the object of Developer class

Error Code.

It’s possible to traverse python_developers or javascript_developers as they are defined as list but we actually can not apply for loop to dev_team (Objet of Developer) until:

1: Developer class has a __iter__ method
2: __iter__ method in the developer class must return iterator of Developer class.

Creating Iterator for Developer class
Adding __iter__ method to developer class which will return Iterator object

And we are able to loop over the object of Developer class

Looping over dev_team (object of developer class)

--

--