Python's enumerate() lets you write Pythonic for loops when you need a count and the value from an iterable. The big advantage of enumerate() is that it returns a tuple with the counter and value, so you don't have to increment the counter yourself.
When you're counting the occurrences of a single object, you can use a single counter. However, when you need to count several different objects, you have to create as many counters as unique objects you have. To count several different objects at once, you can use a Python dictionary.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With