Kodeclik Blog


How to count in a Python loop

Python is such an expressive language that you might have to un-learn a lot of the old style programming habits you might have picked up from other languages.
For instance, the old style way of looping through the characters in a string looks like:
The output will be:
In this program we iterate through the characters of the string knowing that the first index is 0 and the last index is one less than the length of the string. The for loop provides an index (the variable i) which we use inside the loop to fetch the specific character.
Of course if you are a seasoned Python programmer you know that this is not the Python-ic way of doing things. The more elegant solution is:
with the same output as before.
Here the for loop iterates over the string and because strings are iterables in Python each iteration of the for loop fetches one character at a time. The variable “i” here refers to the actual characters in the string “mystring”, not the indices.
What if you would like both? I.e., you wish to iterate over the characters and also need a counter for some purposes? Python provides an elegant way to do that using the enumerate function.
The enumerate function takes as input an iterable (such as a string in our example) and returns two values, one the index and the other the actual value from the iterable.
So you can replace the above program by:
The output will still be:
Note that enumerate returns two variables (a and b) but we are not really using the first variable for anything. Here’s how you can use it to count in a loop:
The output will be:
Note that we are using the str() function to convert the index returned by enumerate (which will be an integer) into a string so that we can use it for concatenation. Also note that indices returned by enumerate() begin at 0, so we are adding 1 for ease of understanding.
Thus, enumerate() is a very useful function for counting inside a loop.
Interested in more things Python? 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 2022. All rights reserved.