Python loop counter in a for loop
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.
Use enumerate()
like so:
def draw_menu(options, selected_index):
for counter, option in enumerate(options):
if counter == selected_index:
print " [*] %s" % option
else:
print " [ ] %s" % option
options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(options, 2)
Note: You can optionally put parenthesis around counter, option
, like (counter, option)
, if you want, but they're extraneous and not normally included.