5

Obviously, if we do this, the counter will remain at 0 as it is reset at the start of every iteration:

for thing in stuff:
    count = 0
    print count
    count =+1
    write_f.write(thing)

But as I have this code inside of function, it does not work to do this either:

count=0
for thing in stuff:
    print count
    count =+1
    write_f.write(thing)

I have several different indent levels, and no matter how I move count=0about, it either is without effect or throws UnboundLocalError: local variable 'count' referenced before assignment. Is there a way to produce a simple interation counter just inside the for loop itself?

ettanany
  • 15,827
  • 5
  • 37
  • 56
DIGSUM
  • 1,611
  • 9
  • 25
  • 39

1 Answers1

25

This (creating an extra variable before the for-loop) is not pythonic .

The pythonic way to iterate over items while having an extra counter is using enumerate:

for index, item in enumerate(iterable):
    print(index, item)

So, for example for a list lst this would be:

lst = ["a", "b", "c"]

for index, item in enumerate(lst):
  print(index, item)

...and generate the output:

0 a
1 b
2 c

You are strongly recommended to always use Python's built-in functions for creating "pythonic solutions" whenever possible. There is also the documentation for enumerate.


If you need more information on enumerate, you can look up PEP 279 -- The enumerate() built-in function.

daniel451
  • 9,128
  • 15
  • 53
  • 115