Loops: Counting as You Go


#1




My code works correctly, but I am curious as to why the 'for' loop requires the following syntax: 'for index, item in enumerate(choices):' instead of just 'for items in enumerate(choices):'... Why is the 'index,item' necessary?


choices = ['pizza', 'pasta', 'salad', 'nachos']

print 'Your choices are:'
for index, item in enumerate(choices):
    print index+1, item


#2

It's not, but you may want those individual values each in their own variables.


#3

So the code would still run properly with 'for item in enumerate(choices):"?

Thanks for your help! It is greatly appreciated :slight_smile:


#4

Hi @boston_woodworth ,

As @ionatan advised, you may want those individual values each in their own variables.

If you do this ...

for items in enumerate(choices):

... you will also have to adjust your print statement. If you adjust it as follows ...

print items

... you will get this output, which you might not like ...

Your choices are:
(0, 'pizza')
(1, 'pasta')
(2, 'salad')
(3, 'nachos')

So, you may want to do this instead ...

print items[0] + 1, items[1]

... to get this better output ...

Your choices are:
1 pizza
2 pasta
3 salad
4 nachos

... but, getting back to what @ionatan said, it would have been cleaner to have each value in its own variable.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.