Sort, and copy before you change
sorted(items) builds a new sorted list. items.sort() sorts the list itself and returns None. A second name for a list is the same list; copy() makes a separate one.
- Choose between
sorted(items)(new list) anditems.sort()(in place) - Explain why
backup = itemsdoesn't protect anything, and useitems.copy() - Tell
==(same items) apart fromis(the same list)
Sorting answers many questions: the cheapest items, the median rating, the top scores. Python gives you two ways to sort.
sorted(items)builds a new list in order and leavesitemsalone.items.sort()rearranges the list itself and returnsNone, likeappenddoes.
Both sort numbers from smallest to largest and text alphabetically. Add reverse=True to get the largest first.
Run each example to see what it prints. Running examples doesn't count toward progress.
scores = [72, 58, 91, 60] print(sorted(scores)) print(scores) print(sorted(scores, reverse=True)) result = scores.sort() print(result, scores) print(sorted(["banana", "Apple", "cherry"]))
Because lists change in place, you need to know which names refer to which list. same = readings doesn't copy anything. It gives the same list a second name, so a change made through either name shows up under both. readings.copy() builds a new list with the same items, and changing one list no longer affects the other.
is tells you whether two names refer to the same list, and == tells you whether two lists hold equal items.
readings = [3.3, 7.2, 6.7] same = readings backup = readings.copy() readings.sort() print(same, same is readings) print(backup, backup is readings) print(backup == [3.3, 7.2, 6.7])
When to use it: use sorted when the original order still matters, for example when you print it later, and .sort() when you no longer need it. Copy a list before changing it if someone else still needs the original. Mistakes to avoid:
items = items.sort(), which leaves you with None.- Thinking
b = amakes a backup. - Sorting text with mixed capitals and expecting dictionary order.
sorted(items)returns a new sorted list.items.sort()sorts in place and returns None.reverse=Trueputs the largest first.b = agives the same list a second name.a.copy()makes a separate list.==compares items, andisasks whether two names refer to the same list.- Next: give each value in a tuple its own name by unpacking it.