15/19: Doubt about enumerate() function syntax


#1

Whenever we use the enumerate function, is the syntax always:

for index,item in enumerate(choices):

With index and item as placeholders? (I can use other placeholders like k, for key, and v for value, right?)
I mean, can I print out only the index or only the item using enumerate?
(Of course there are other ways to do that and it makes little sense doing it with enumerate, but still, can it be done?)


#2

they are not really placeholder, they are variable defined (technically variable are named in python, not defined) at this line, then for and enumerate() will assign index and item from the list to these variables.

given the variable are defined at the for loop, we can name the variable anything we like. But index and item are very logic variable names (logic variable names, very important in programming)

no, given you have both values in a variable, you can perfectly print both:

for index,item in enumerate(choices):
    print index, item

if you only want index or item you wouldn’t use enumerate:

# items
for item in choices:
   print item

# indexes
for index in range(len(choices)):
   print index

enumerate make sense if you you need both index and item.


#3

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