What is the easiest way to iterate through files while maintaining a counter?

What is the cleanest code iterating through the lines of a text file while increasing the counter?

I understand that with multiple assignment there is a cleaner syntax than

i = 0 for line in f: ... ++i 
+4
source share
2 answers
 for i, line in enumerate(f): print i, line 

As shown here: http://docs.python.org/library/functions.html#enumerate

+12
source
 for count, line in enumerate(f): 

Enumeration starts at index 0, unless otherwise specified, provided that the counter is repeated at the same time as each element of the for loop

EDIT: as a side note, you can change where the enumeration starts with the second argument, for example. for count, line in enumerate(f, 11) will cause it to start at 11

+9
source

Source: https://habr.com/ru/post/1344332/


All Articles