variable length print format

holger krekel pyth at devel.trillke.net
Tue May 7 15:37:30 EDT 2002


les ander wrote:
> Hi,
> i have a variable length list of numbers.
> i would like to print them out with indicies in front as shown below:
> 
> List=['a','b','c','d'] ---> 1:a 2:b 3:c 4:d
> 
> one obvious solution is that i do
> for i in range(List):
>   print "%s:%s" % (i+1,List[i])

you could use PEP279 from GvR:

from __future__ import generators # requires 2.2
def enumerate(collection):
    'Generates an indexed series:  (0,coll[0]), (1,coll[1]) ...'     
    i = 0
    it = iter(collection)
    while 1:
        yield (i, it.next())
        i += 1

for i,s in enumerate(['a','b','c']):
    print str(i)+':'+s

enumerate will be an included battery in python2.3
and is quite fast and convenient. 

Of course you can also do weird stuff like e.g.

l=['a','b','c','d']
print '\n'.join(map(lambda x: '%s:%s' % x, zip(range(len(l)),l)))

to avoid any for-loops. But i'd prefer the enumerate 
construct for obvious reasons.
 
regards,

    holger





More information about the Python-list mailing list