In Python, using a counter-based loop to iterate over a sequence, as in
string = 'ab'
for index in range(len(string)):
print(index)
print(string[index])
which prints 0
, a
, 1
, and b
, is not considered idiomatic.
Instead, Python code typically uses enumerate
objects.
The enumerate
constructor takes a sequence and builds another sequence-like object holding tuples. The
first element of each tuple is an index, and the second element of each tuple is the value at that index in the
original sequence. An enumerate
object can be iterated over once. For example, the code from above
could be written
string = 'ab'
for pair in enumerate(string):
print(pair[0]) # the first part of the tuple is the index
print(pair[1]) # the second part of the tuple is the element at that index
But this is still not preferred style because typically the parts of the tuple will be named separately in the for-each loop, as below:
string = 'ab'
for index, letter in enumerate(string):
print(index)
print(letter)
Fill in the placeholders so that the actual outputs match the expected outputs.