Currently working my way through this beginners book and have completed one of the practice projects \'Comma Code\' which asks the user to construct a program which:
This is what I came up with. There's probably a much cleaner way to write this, but this should work with any sized list as long as there's at least one element in the list.
spam = ['apples', 'oranges' 'tofu', 'cats']
def CommaCode(list):
if len(list) > 1 and len(list) != 0:
for item in range(len(list) - 1):
print(list[item], end=", ")
print('and ' + list[-1])
elif len(list) == 1:
for item in list:
print(item)
else:
print('List must contain more than one element')
CommaCode(spam)