runtime
34 / 250
lesson 34 Lists & Tuples · beginner

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.

You'll be able to
  • Choose between sorted(items) (new list) and items.sort() (in place)
  • Explain why backup = items doesn't protect anything, and use items.copy()
  • Tell == (same items) apart from is (the same list)
The idea

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 leaves items alone.
  • items.sort() rearranges the list itself and returns None, like append does.

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.

example-1.py · sorted versus sort
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.

example-2.py · A second name is not a copy
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 = a makes a backup.
  • Sorting text with mixed capitals and expecting dictionary order.
Review
  • sorted(items) returns a new sorted list. items.sort() sorts in place and returns None. reverse=True puts the largest first.
  • b = a gives the same list a second name. a.copy() makes a separate list.
  • == compares items, and is asks whether two names refer to the same list.
  • Next: give each value in a tuple its own name by unpacking it.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Sort, and copy before you change — Lists & Tuples · Runtime