enumerate
is used to generate a line index, the i
variable, together with the line
string, which is the i-th line in the text file. Getting an index from an iterable is such a common idiom on any iterable
that enumerate
provides an elegant way to do this. You could, of course, just initialize an integer counter i
and increment it after each line is read, but enumerate does that for you. The main advantage is code readability: the i
variable initialization and increment statements would be book-keeping code that is not strictly necessary to show the intent of what that loop is trying to do. Python excels at revealing the business-logic of code being concise and to the point.
You can look at Raymond Hettinger’s presentation to learn more about idiomatic python from these excellent notes.
3
solved What Does Enumerate Do in This Context [Python]