I'm currently learning Python through Codecademy. One of the exercises uses this in it's for loop:
choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are:'
for index, item in enumerate(choices):
print index + 1, item
I've only seen things like:
for i in list:
That being said, I don't understand what the "index," part of the loop is, or what it's function is. All I understand from this is that it will index each item in the list, and print them. Thanks in advance.
Enumerate makes a list
of tuple
which are (index, element)
.
l = ['thing', 'foo', 'bar', 'doodad']
list(enumerate(l))
This is the output of enumerate
[(0, 'thing'), (1, 'foo'), (2, 'bar'), (3, 'doodad')]
You can unpack
these tuples and do whatever you'd like with each component of the tuple.
for index, element in enumerate(l):
print 'index', index
print 'element', element
index 0
element thing
index 1
element foo
index 2
element bar
index 3
element doodad