The suggestion that using range(len()) is equivalent to using enumerate() is incorrect. They return the same results, but they do not match.
Using enumerate() really gives you key / value pairs. Using range(len()) does not work.
First check range(len()) (working from the example from the original poster):
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh'] print range(len(words))
This gives us a simple list:
[0, 1, 2, 3, 4]
... and the items in this list serve as βindicesβ in our results.
So do the same with our version of enumerate() :
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh'] print enumerate(words)
This, of course, does not give us a list:
<enumerate object at 0x7f6be7f32c30>
... so put it on the list and see what happens:
print list(enumerate(words))
This gives us:
[(0, 'aba'), (1, 'xyz'), (2, 'xgx'), (3, 'dssd'), (4, 'sdjh')]
These are actual key / value pairs.
So this is ...
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh'] for i in range(len(words)): print "words[{}] = ".format(i), words[i]
... actually takes the first list (Words) and creates a second, simple range list, indicated by the length of the first list.
So, we have two simple lists, and we just print one item from each list to get our so-called key / value pairs.
But they are not really key / value pairs; these are just two separate items printed at the same time from different lists.
While the enumerate () code is:
for i, word in enumerate(words): print "words[{}] = {}".format(i, word)
... also creates a second list. But this list is actually a list of key / value pairs, and we request each key and value from one source, and not from two lists (for example, we did above).
So, we print the same results, but the sources are completely different - and they are processed in a completely different way.