]Ernesto García García] > it's very common that I have a list and I want to print it with commas > in between. How do I do this in an easy manner, whithout having the > annoying comma in the end? > > <code> > > list = [1,2,3,4,5,6] > > # the easy way > for element in list: > print element, ',', > > print > > > # this is what I really want. is there some way better? > if (len(list) > 0):
More idiomatic as if len(list) > 0: and even more so as plain if list: > print list[0], > for element in list[1:]: > print ',', element, Do you really want a space before and after each inter-element comma? > </code> An often-overlooked alternative to playing with ",".join() is: print str(list)[1:-1] That is, ask Python to change the list into a big string, and just strip the brackets off each end: >>> alist = ['a, bc', 4, True] >>> print str(alist)[1:-1] 'a, bc', 4, True Note the quotes around the string element! This differs from what your code snippet above would produce (in addition to differing wrt spaces around inter-element commas): a, bc , 4 , True -- http://mail.python.org/mailman/listinfo/python-list