May-08-2023, 12:25 PM
You could print the return value if you want to see the results.
As for "the wrong way", using a mutable type for a default argument can cause problems, but it does not in your code. The default argument is there to protect against calling the function without any arguments. I think it makes more sense to let the function crash if no list is provided, but the author decided they would return an empty string when this happens.
A larger problem with the code is it limits you to sorting lists. You cannot sort a tuple or a set. I would rewrite to make it work with any itrator.
Another problem is the function can be replaced with a single line of code.
As for "the wrong way", using a mutable type for a default argument can cause problems, but it does not in your code. The default argument is there to protect against calling the function without any arguments. I think it makes more sense to let the function crash if no list is provided, but the author decided they would return an empty string when this happens.
A larger problem with the code is it limits you to sorting lists. You cannot sort a tuple or a set. I would rewrite to make it work with any itrator.
def alphabetize(items=[]): """Return sorted list as CSV string.""" final_list = '' for name in sorted(items): final_list += name + ', ' final_list = final_list[:-2] return final_list names = {'McMullen', 'Keaser', 'Maier', 'Wilson', 'Yudt', 'Gallagher', 'Jacobs'} print(alphabetize(names))Using "sorted()" instead of "sort()" we don't have to copy the input list. sorted() creates the new, sorted list for us. Since we don't have to copy() the input, we don't have to pass in a list. In my example I passed in a set. I could also pass a tuple, or a generator, or any iterable (thing that can be used in a for loop).
Another problem is the function can be replaced with a single line of code.
names = {'McMullen', 'Keaser', 'Maier', 'Wilson', 'Yudt', 'Gallagher', 'Jacobs'} print(",".join(sorted(names)))But these are only problems if this was "production code", not if it is a coding example for learning Python. It is difficult to write code that is both well designed and demonstrates the intent of the lesson. Maybe the next lesson will point out the shortcomings of limiting the function input to a list, and the advantages of using the builtin function and standard libraries instead of writing your own.