Comma Code - Automate the Boring Stuff with Python 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)
You've got an odd bug with your code.

Given the 8th menu item from the greasy spoon café:

spam = ["Spam", "Spam", "Spam", "egg", "Spam"]


You will get:


  and Spam
  and Spam
  and Spam
  egg, and Spam


since you are not testing whether you are at the last item in your list, but rather if the current item is the same as the last item in the list.



Testing for a length 1 list should not be done inside the loop of all items; it should be done exactly once, outside the loop.  Ie (but still with the above bug):

if len(list) == 1:    # Test outside of loop
   print(list[0]) 
else:
    for item in list:
        if item != list[-1]:
            print(item + ', ', end='')
        else:
            print('and ' + list[-1])




Want you really want to do is print all but the last item in the list one way, and the last item a different way:

# If there are more than 1 items in the list...
if len(list) &gt; 1:

    # Print all but the last item, with a comma &amp; space after each
    for item in list[:-1]:
        print(item + ', ', end='')

    # with "and " printed at the very end, just before ...
    print("and ", end='')

# print the last (or only) item in the list.
print(list[-1])


although this still assumes at least one item in the list.



Alternately, you could join() all but the last item, and then add ", and " along with the final item.

msg = list[-1]
if len(list) &gt; 1:
    msg = ", ".join(list[:-1]) + ", and " + msg
print(msg)




You are doing import sys, but not using sys anywhere.  You can remove the import.