variable length print format

Jeff Shannon jeff at ccvcorp.com
Tue May 7 15:59:26 EDT 2002


In article <a2972632.0205071050.9e68201 at posting.google.com>, les 
ander says...
> 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])
> 
> however i have a lot of these and would like it to be faster ...

One way to do this, though they really won't be much faster:

>>> mylist = ['a', 'b', 'c', 'd']
>>> indexedlist = zip(range(1,len(mylist)+1),mylist)
>>> " ".join( [ "%d:%s" % (I,v) for I,v in indexedlist ] )
'1:a 2:b 3:c 4:d'
>>>

But no matter how you do this, you're going to be looping over 
the contents of your list.  Whether it's better to loop once at 
python level, as you're doing, or twice at C level, as my code 
does, is an open question -- you'd have to time both of them on a 
variety of sizes of list. 

Of course, the other question is, how much "faster" do you need 
it?  Unless this is a demonstrable bottleneck in your program, 
you're best off just creating a simple, easy-to-understand 
function, and using that everywhere.

>>> def indexlist(sequence):
... 	strings = []
... 	for i in range(len(sequence)):
... 		strings.append( "%d:%s" % (i+1, sequence[i]) )
... 	return " ".join(strings)
... 
>>> mylist = ['a', 'b', 'c', 'd']
>>> print indexlist(mylist)
1:a 2:b 3:c 4:d
>>> 

This way, it's easy to use (provided you name your function 
something sensible).  It's *also* easy to change if, for example, 
you decide that you want each item printed on a separate line 
with the indexes right-justified.

>>> def indexlist(sequence):
... 	strings = []
... 	for i in range(len(sequence)):
... 		strings.append( "%3d:%s" % (i+1, sequence[i]) )
... 	return "\n".join(strings)
... 
>>> print indexlist(mylist)
  1:a
  2:b
  3:c
  4:d
>>> 

-- 

Jeff Shannon
Technician/Programmer
Credit International



More information about the Python-list mailing list