Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a counter inside a Python for loop [duplicate]

Tags:

python

loops

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?

like image 665
DIGSUM Avatar asked Dec 01 '16 14:12

DIGSUM


People also ask

How do you keep a counter in a for loop Python?

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.

Can you have multiple counters in Python?

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.


1 Answers

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.

like image 139
daniel451 Avatar answered Oct 26 '22 08:10

daniel451