Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a function that will increment by one when called

Tags:

python

count

I am needing a function that will increment by one every time it is called. I have used count but every time I do it resets the count back to the original value plus one count. I have seen lots of code but none of it works. Here is what I have now

I have done lots of looking into loops and iterations

def count_row():
    count = 1  
    while count >= 1:
        yield count
        count += 1 
return count
like image 751
nmhammer Avatar asked Mar 05 '26 07:03

nmhammer


1 Answers

You can use itertools.count.

from itertools import count

counter = count(1)
next(counter) # 1
next(counter) # 2

Stateful function

If you absolutely want a stateful function instead of calling next, you can wrap the count in a function.

def counter(_count=count(1)):
    return next(_count)

counter() # 1
counter() # 2

Class

Alternatively, itertools.count being a class, you can inherit from it to extend it's behaviour and make it a callable.

class CallableCount(count):
    def __call__(self):
        return next(self)

counter = CallableCount(1)

counter() # 1
counter() # 2

Using a class would be my preferred approach since it allows instantiating multiple counters.

like image 126
Olivier Melançon Avatar answered Mar 07 '26 20:03

Olivier Melançon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!