I'm working on a list practice project from the book "Automate the Boring Stuff with Python" which asks for this:
Write a function that takes a list value 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 value passed to it. Be sure to test the case where an empty list [] is passed to your function.
So far I've come up with this:
def comma_code(iterable):
'''
Function that loops through every value in a list and prints it with a comma after it,
except for the last item, for which it adds an "and " at the beginning of it.
Each item is str() formatted in output to avoid concatenation issues.
'''
for i, item in enumerate(iterable):
if i == len(iterable)-1 and len(iterable) != 1: # Detect if the item is the last on the list and the list doesn't contain only 1 item (BONUS)
print('and ' + str(iterable[-1])) # Add 'and ' to the beginning
elif len(iterable) == 1: # BONUS: If list contains only 1 item,
print('Just ' + str(iterable[-1])) # replace 'and ' with 'Just '
else: # For all items other than the last one
print(str(iterable[i]) + ',', end=" ") # Add comma to the end and omit line break in print
There's heavy commenting because I'm fairly new and I'm trying to leave everything as clear as possible for my future self.
Now I wonder if there's a better way of doing this and also (subjective question) if there is something in my code that I should change for better readability and/or style. As I said, I'm fairly new and I would like to pick good coding practices from the beginning.
These are a couple of lists I ran through the function:
spam = ['apples', 'bananas', 'tofu', 'cats']
bacon = [3.14, 'cat', 11, 'cat', True]
enty = [1]
And this is the working output:
apples, bananas, tofu, and cats
3.14, cat, 11, cat, and True
Just 1
Thanks in advance.