DEV Community

natamacm
natamacm

Posted on

Iterators in Python

In Python there are several ways to loop over data. While many programming languages only come with loops (for loops, while loops), in Python you also have a thing named iterators.

An iterator is a tool used to iterate a value, and an iteration is the activity of a repeated feedback process.

Each repetition of the process is called an "iteration", and the result obtained from each iteration is the value.

For loops

The default way to loop over data is by using for loops.

The for loop below has five iterations, because the length of the list is five.

goods=['apple','sony','lenovo','acer','dell']

index=0
while index < len(goods):
    print(goods[index])
    index+=1

For loops can be used for simple implementation by iterating the value by indexing, but only for sequence types: strings, lists, tuple groups.

Iterators

For non-sequential types such as dictionaries, collections, file objects, etc. that do not have an index, one must find a way to iterate the value that does not depend on the index, and this can lead to the use of iterators.

A call to the obj.iter() method returns an iterator object (Iterator).

In addition to file objects, dictionaries, collections, lists, etc. are just iteratable objects that can generate iterator objects and iteratively take values by calling the iter() method.

Then by calling the next() method on the iterator object you get the next value.

>>> s={1,2,3} 
>>> i=iter(s)
>>> next(i)
1
>>> next(i)
2
>>> next(i)
3
>>> next(i)  # StopIteration exception

You can use an iterator object to iterate over a dictionary, the program below shows an example of that:

dic = {'a':1,'b':2,'c':3}
d_iterator = iter(dic) # d_iterator

while True: 
    try:
        print(next(d_iterator))
    except(StopIteration):
        break 

Related links:

Top comments (0)