Kodeclik Blog


The next function in Python

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.
For more Python content, checkout the math.ceil() and math.floor() functions! Also learn about the math domain error in Python and how to fix it!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2023. All rights reserved.