You will need to consider the case when you have only one element:
def comma_separator(sequence): if not sequence: return '' if len(sequence) == 1: return sequence[0] return '{} and {}'.format(', '.join(sequence[:-1]), sequence[-1])
Note that bool(sequence) is True is a very complex test method for a non-empty list; just using if sequence: enough, because the if already looking for a logical truth.
Perhaps calling a function with anything but a sequence (something that can be indexed and has a length) should just throw an exception. Usually you do not check types in such functions. If you need to check the type, use isinstance(sequence, list) to at least allow subclasses.
I would also make a mistake to go to the empty list. You can turn this exception into a ValueError :
def comma_separator(sequence): if len(sequence) > 1: return '{} and {}'.format(', '.join(sequence[:-1]), sequence[-1]) try: return sequence[0] except IndexError: raise ValueError('Must pass in at least one element')
Demonstration of the latter:
>>> def comma_separator(sequence): ... if len(sequence) > 1: ... return '{} and {}'.format(', '.join(sequence[:-1]), sequence[-1]) ... try: ... return sequence[0] ... except IndexError: ... raise ValueError('Must pass in at least one element') ... >>> comma_separator(['foo', 'bar', 'baz']) 'foo, bar and baz' >>> comma_separator(['foo', 'bar']) 'foo and bar' >>> comma_separator(['foo']) 'foo' >>> comma_separator([]) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 7, in comma_separator ValueError: Must pass in at least one element
source share