Below is my code for the Comma Code problem from Chapter 4 of Automate the Boring Stuff with Python. Is there anything I can do to make it cleaner?
Comma Code
Say you have a list value like this:
spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list of values as an argument and returns a string with all the items separated by a comma and a space, with 'and' inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list passed to it.
The output of this program could look something like this: apples, bananas, tofu, and cats
import sys
spam = ['apples', 'bananas', 'tofu', 'cats']
def print_list(list):
for item in list:
if len(list) == 1:
print(list[0])
elif item != list[-1]:
print(item + ', ', end='')
else:
print('and ' + list[-1])
print_list(spam)