Consider an “iterable” data structure such as a string. Iterable refers to the property that the parts of this data structure are organized in an order so you can proceed from the beginning to the end.
Consider a string as follows:
Because a string is an iterable, you can write a for loop such as below:
The output will be:
You cannot do this with an integer for instance:
This code will yield:
As the message clearly indicates, an integer object (in our case, 23) is not iterable.
The next() function applies to iterables such as the “mystring” string above. The next() function takes an iterator as an input. So you need to first create an iterator as follows:
In the above code, we use the iter() function that takes a string and returns an iterator (stored in “string_iterator”). Then we iterate through the string by using the next() function that returns characters one at a time, and print the returned character.
The output will be:
Note what has happened. After indeed iterating and printing the characters in “Kodeclik” we get an error. This is because the iterator has reached the end of the string and we tried to push it beyond the end of the string and thus obtained a “StopIteration” message.
The next() function actually provides a very handy way to determine when you have reached the end of the iteration:
In the above code, we call the next() function with an iterator (as before) and now a second argument (called “stop”). This means that when the iterator reaches the end of the iteration next() is expected to return “stop”. Inside the loop, we see if “stop” is returned, in which case we break out of the loop and only print the character otherwise.
Now the output will be:
As intended, we do not obtain any error message now.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.