'''data0.py Jed Yang, 2016-11-12 An example of destructive functions. ''' print('Sorting using sorted()') array = ['violet', 'daisy', 'ivy', 'rose'] print('input:', array) result = sorted(array) print('result:', result) print() # So far so good. print('Sorting using .sort()') array = ['violet', 'daisy', 'ivy', 'rose'] print('input:', array) result = array.sort() print('result:', result) print() # There are no errors reported, but why is it printing result: None? # Hint: print the original array out to see what's going on. # .sort() is a method that "destroys" what you had and changes it. We say that # it sorts "in-place." We have discussed the benefit of sorting in-place: we # do not need to create extra space to hold data. (Imagine if the list is # really, really long; do you want two copies of it? Maybe not.) # Python tries to remind you that .sort() sorts in-place by returning None. # This is a feature, not a bug. Indeed, if you are confused why you get None, # you may then remember that you should just keep using 'array' instead, since # it is now the sorted version of itself. If Python had changed the list AND # return the list, you may very well forget that the original list has been # changed. # You can try to print the original array in the first example after sorting to # be sure that array was not changed when using sorted().