Small problem with print and comma

Tim Chase python.list at tim.thechases.com
Sun Jul 30 19:13:56 EDT 2006


> I have a small problem with my function: printList. I use print with a
> ',' . Somehow the last digit of the last number isn't printed. I wonder
> why.

Posting actual code might help...the code you sent has a horrible 
mix of tabs and spaces.   You've also got some craziness in your 
"creating random list" string.  First off, it looks like you're 
using a docstring, but they only go immediately after the def 
line.  I'd recommend putting it where it belongs, or changing the 
line to a comment.

There are some unpythonic bits in here:

printList() would usually just idiomatically be written as

	print ' '.join(a)

although there are some int-to-string problems with that, so it 
would be written as something like

	print ' '.join([str(x) for x in listOfNumbers])

which is efficient, and avoids the possibility of off-by-one 
errors when range(0,length).

Another idiom would be the list-building of createRandomList:

return [random.randrange(100) for x in xrange(0,length)]

Additionally, this can be reduced as range/xrange assume 0 as the 
default starting point

return [random.randrange(100) for x in xrange(length)]

(using xrange also avoids building an unneeded list, just to 
throw it away)

Additionally, rather than rolling your own bubble-sort, you can 
just make use of a list's sort() method:

a.sort()

Other items include sensibly naming your parameters rather than 
generically calling them "param", just to reassign them to 
another name inside.

Taking my suggestions into consideration, your original program 
condenses to

########################################

import random

def createRandomList(length):
     return [random.randrange(100) for x in xrange(length)]

def printList(listOfNumbers):
     print ' '.join([str(x) for x in listOfNumbers])

if __name__ == "__main__":
     length = 10
     a = createRandomList(length)
     printList(a)
     a.sort()
     print "sorted list"
     printList(a)

########################################

one might even change createRandomList to allow a little more 
flexibility:

def createRandomList(length, maximum=100):
     return [random.randrange(maximum) for x in xrange(length)]


So it can be called as you already do, or you can specify the 
maximum as well with

	createRandomList(10, 42)

for future use when 100 doesn't cut it for you in all cases.

Just a few thoughts.

-tkc







More information about the Python-list mailing list