How to Auto-Increment in Python

How to Auto-Increment in Python

I am new to python. I want to print all available functions in os module as:

1 functionName

2 functionName

3 functionName

and so on.

Currently I am trying to get this kind of output with following code:

import os

cur = dir(os)
for i in cur:
    count = 1
    count += 1
    print(count,i)

But it prints as below:

2 functionName

2 functionName

2 functionName

till end.

Please help me generate auto increment list of numbers, Thanks.

5

2 Answers

Its because you've re-defined the count variable or reset it to 1 for each loop again. I'm not into python but your code doesn't make sense since everytime the count variable is first set to 1 and then incremented. I'd simply suggest the following.

import os

cur = dir(os)
count = 1
for i in cur:
    count += 1
    print(count,i)
0

The pythonic way to do this is enumerate. If we pass the keyword argument start=1, the count will begin at 1 instead of the default 0.

import os

cur = dir(os)
for i, f in enumerate(cur, start=1):
    print("%d: %s" % (i, f))
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.