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=0
about, 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?
Use the enumerate() function to count in a for loop, e.g. for index, item in enumerate(my_list): . The function takes an iterable and returns an object containing tuples, where the first element is the index, and the second - the item.
When you're counting the occurrences of a single object, you can use a single counter. However, when you need to count several different objects, you have to create as many counters as unique objects you have. To count several different objects at once, you can use a Python dictionary.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With