[loops] Python loop counter in a for loop

In my example code below, is the counter = 0 really required, or is there a better, more Python, way to get access to a loop counter? I saw a few PEPs related to loop counters, but they were either deferred or rejected (PEP 212 and PEP 281).

This is a simplified example of my problem. In my real application this is done with graphics and the whole menu has to be repainted each frame. But this demonstrates it in a simple text way that is easy to reproduce.

Maybe I should also add that I'm using Python 2.5, although I'm still interested if there is a way specific to 2.6 or higher.

# Draw all the options, but highlight the selected index
def draw_menu(options, selected_index):
    counter = 0
    for option in options:
        if counter == selected_index:
            print " [*] %s" % option
        else:
            print " [ ] %s" % option
        counter += 1


options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']

draw_menu(option, 2) # Draw menu with "Option2" selected

When run, it outputs:

 [ ] Option 0
 [ ] Option 1
 [*] Option 2
 [ ] Option 3

This question is related to loops for-loop python

The answer is


I'll sometimes do this:

def draw_menu(options, selected_index):
    for i in range(len(options)):
        if i == selected_index:
            print " [*] %s" % options[i]
        else:
            print " [ ] %s" % options[i]

Though I tend to avoid this if it means I'll be saying options[i] more than a couple of times.


You could also do:

 for option in options:
      if option == options[selected_index]:
           #print
      else:
           #print

Although you'd run into issues if there are duplicate options.


enumerate is what you are looking for.

You might also be interested in unpacking:

# The pattern
x, y, z = [1, 2, 3]

# also works in loops:
l = [(28, 'M'), (4, 'a'), (1990, 'r')]
for x, y in l:
    print(x)  # prints the numbers 28, 4, 1990

# and also
for index, (x, y) in enumerate(l):
    print(x)  # prints the numbers 28, 4, 1990

Also, there is itertools.count() so you could do something like

import itertools

for index, el in zip(itertools.count(), [28, 4, 1990]):
    print(el)  # prints the numbers 28, 4, 1990

Examples related to loops

How to increment a letter N times per iteration and store in an array? Angular 2 Cannot find control with unspecified name attribute on formArrays What is the difference between i = i + 1 and i += 1 in a 'for' loop? Prime numbers between 1 to 100 in C Programming Language Python Loop: List Index Out of Range JavaScript: Difference between .forEach() and .map() Why does using from __future__ import print_function breaks Python2-style print? Creating an array from a text file in Bash Iterate through dictionary values? C# Wait until condition is true

Examples related to for-loop

List append() in for loop Prime numbers between 1 to 100 in C Programming Language Get current index from foreach loop how to loop through each row of dataFrame in pyspark TypeScript for ... of with index / key? Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? Python for and if on one line R for loop skip to next iteration ifelse How to append rows in a pandas dataframe in a for loop? What is the difference between ( for... in ) and ( for... of ) statements?

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation