Simon S Simon S - 3 months ago 5
Python Question

Converting a list into comma-separated string with "and" before the last item - Python 2.7

I have created this function to parse the list:

listy = ['item1', 'item2','item3','item4','item5', 'item6']


def coma(abc):
for i in abc[0:-1]:
print i+',',
print "and " + abc[-1] + '.'

coma(listy)

#item1, item2, item3, item4, item5, and item6.


Is there a neater way to achieve this?
This should be applicable to lists with any length.

Answer

When there are 1+ items in the list (if not, just use the first element):

>>> "{} and {}".format(", ".join(listy[:-1]),  listy[-1])
'item1, item2, item3, item4, item5, and item6'

Edit: If you need an Oxford comma (didn't know it even existed!) -- just use: ", and" isntead.

Comments