3) g. Iterators and Iterables

The distinction between iterators and iterables may seem confusing at first but there is a logic to it.

Let’s start with iterables. An iterable is an object that can be iterated over. In other words, it is an object that has multiple values and you can get those values one-at-a-time.

An example would be a string or a list.

1
2
3
4
5
6
7
8
9
10
11
12
13
Output:
H
e
l
l
o
 
w
o
r
l
d
!



Here you are also introduced to the concept of for-loop. The for-loop basically allows you to pick up each item, one by one, in the given list, string, set or tuple (iterables). As you can see from the output, “char” assumes the value of every character one by one.

In the previous example, the string that we’re running over is called an iterable. “Hello world” is an iterable.

An iterator on the other hand is an object that allows you to receive the next item from an iterable or break when there are no more items left. In fact, the for loop uses an iterator char in the background!

1
2
3
4
Output:
H
e
l

In this example you create your own iterator for a string and then ask it for next items (characters) three times.

It is almost never convenient to iterate over iterables by creating your own iterator but you should know how this process works.

A few important things to note:

  • An iterator can fetch elements only in forward direction.
  • Once you’ve fetched an element you cannot fetch it again because the iterator would have moved forward.
  • After the iterator has reached the last element you cannot use that iterator to start over again. Instead, you can create a new iterator.
  • After you have fetched the last element if you try to fetch one more element using next() then the iterator will throw an error and your program will terminate.

So you need to typically put a limit to how many times you call next().

1
2
3
4
5
6
7
Output:
h
e
l
l
o
StopIteration:  on line 12




To prevent this error you could keep a counter that ensures you don’t exceed the last character.

1
2
3
4
5
6
7
Output:
size_greeting =  5
h
e
l
l
o




You can iterate over any collection like tuples, lists, dictionaries or sets. In case of dictionaries, you would iterate over the keys.

In the following example, notice how we’re saving the next element into a temporary variable so that we can work with it.

1
2
3
4
Output:
Size of dictionary =  2
Baa  :  Black sheep
Wool  :  Three bags full




Here is a summary of the concepts that we’ve covered in this chapter.