Reputation: 147
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.
Upvotes: 8
Views: 66823
Reputation: 21619
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))
Upvotes: 6
Reputation: 1241
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)
Upvotes: 20