Monday, 24 November 2008

Printing comma-separated lists

If there's one thing that really bugged me when forced to write code (well, there are many, many things that bug me, but this is high on the list), it's printing out a comma-separated list, and not have that last pesky comma ruin everything at the end.

So then there's all this fuss about checking whether the item is last in the list and not slot in a comma, but oh wait! what if the list is empty, blah blah blah.

Python makes it easy -- use a join:

', '.join(list)

Done; finished; end of story.

I love Python ...

No comments: