Comma Code - Automate the Boring Stuff with Python
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.