Search code examples
pythoncoding-stylepep

Pythonic way of maintaining counter variables?


I have this kind of code:

count = 0

for line in lines:

    #do something with line
    #do something more with line
    #finish doing that thing with line

    count = count + 1
    if count % 10000 == 0:
        print count

Is this the right way of maintaining count-variable in python? Can I make it look better?


Solution

  • You can use enumerate():

    for count, line in enumerate(lines):
        #do something here
    

    enumerate() also accepts an optional second parameter start, you can use that to specify the start value of count. Default value of start is 0.

    help on enumerate:

    >>> help(enumerate)
    
     |  enumerate(iterable[, start]) -> iterator for index, value of iterable
     |  
     |  Return an enumerate object.  iterable must be another object that supports
     |  iteration.  The enumerate object yields pairs containing a count (from
     |  start, which defaults to zero) and a value yielded by the iterable argument.
     |  enumerate is useful for obtaining an indexed list:
     |      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...