The .sort() Method
Lists also have a method for sorting, .sort(). Unlike sorted(), it doesn't create a new list. It sorts the list it belongs to, so the list itself changes:
scores = [72, 45, 90, 38, 64]
scores.sort()
print(scores)[38, 45, 64, 72, 90]The old order is gone: scores now holds the sorted elements.
Like .append(), .sort() only changes the list and returns None. That leads to a typical mistake, storing what it returns:
names = ["Tom", "Anna", "Max"]
names = names.sort()
print(names)NoneThe list was sorted, but then the assignment names = stored what .sort() returned, None, and the list is lost. For the same reason, print(names.sort()) prints None. Write .sort() on a line of its own, and use the list on the next line.
Only lists have .sort(). A tuple can't be changed, and a set has no order, so neither of them can sort itself:
point = (3, 1, 2)
point.sort()Traceback (most recent call last):
File "<exec>", line 2, in <module>
AttributeError: 'tuple' object has no attribute 'sort'For them, use sorted(). It gives you a sorted list and leaves the tuple or the set as it was.
So which one should you use? sorted() when you still need the original order, or when what you sort isn't a list. .sort() when you have a list and don't need its old order anymore.
Instructions
- 1
The program should print the shopping list in alphabetical order, but it prints
None. Fix it: sort the listshoppingitself with.sort(), without storing what the method returns. The program then prints['apples', 'bread', 'butter', 'milk']. - 2
Below, add
"eggs"to the end of the list with.append()and print the list again. The eggs are at the end:.sort()sorted the list once, when you called it, and doesn't keep it sorted. Then sort the list again and print it once more. The last two lines should be['apples', 'bread', 'butter', 'milk', 'eggs']and['apples', 'bread', 'butter', 'eggs', 'milk']. Leave the first line of the program as it is: the exercise also runs your program with another shopping list.