First of all, the first way is ugly: You either need a separate variable assignment to get the element or use a[i]
all the time which could theoretically be an expensive operation. Imagine a
being a database cursor: When you iterate it (a.__iter__
being called) the object can safely assume that you are going to iterate over all its items. So all or at least multiple rows could be retrieved at once. When getting the length such an optimization would be stupid though since you surely don't want to retrieve data just because you want the number of items. Also, when retrieving a specific item you cannot assume that other items will be retrieved, too.
Additionally, using enumerate()
works with any iterable while range(len())
only works with countable, indexable objects.