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

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.


def oxford_comma_join(l):
    if not l:
        return ""
    elif len(l) == 1:
        return l[0]
    else:
        return ', '.join(l[:-1]) + ", and " + l[-1]

print(oxford_comma_join(['item1', 'item2', 'item3', 'item4', 'item5', 'item6']))

Output:

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

Also as an aside the Pythonic way to write

for i in abc[0:-1]:

is

for i in abc[:-1]:

def coma(lst):
    return '{} and {}'.format(', '.join(lst[:-1]), lst[-1])