Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto-increment in python

Tags:

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.

like image 812
Yethrosh Avatar asked Oct 28 '16 03:10

Yethrosh


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)
like image 190
Pragun Avatar answered Oct 05 '22 23:10

Pragun


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))
like image 27
Paul Rooney Avatar answered Oct 06 '22 01:10

Paul Rooney