Loops, and where your data lives

INPUT · Slides

Putting them in order

01 / 07

You want them tidy

Scores from high to low, names in alphabetical order. Sorting is something you do almost every time you show data to a person.

You could write the comparing and swapping yourself, but Python comes with tools for it. There are two of them, and telling them apart is the hard part of this lesson.

02 / 07

sorted returns a new list

The first is sorted. Hand it a list in the brackets and a new, sorted list comes back.

The important bit: the original is untouched. It builds a new one and returns that, leaving what you gave it alone.

scores = [80, 45, 95]ordered = sorted(scores)print(ordered)print(scores)

Result

[45, 80, 95]
[80, 45, 95]

03 / 07

sort changes the one you have

The second is sort, called with a dot as scores.sort(). This one sorts the list itself.

Same "call it with a dot" shape as append. Things called with a dot usually work on themselves — a handy rule of thumb.

scores = [80, 45, 95]scores.sort()print(scores)

Result

[45, 80, 95]

04 / 07

sort returns nothing

Here is the big trap. sort sorts, and returns nothing at all.

So print(scores.sort()) shows None, which means "nothing there". Worse, scores = scores.sort() replaces your list with None and loses it.

If you want the sorted list, call sort() and then carry on using the same variable.

scores = [80, 45, 95]print(scores.sort())

Result

None

05 / 07

Sorting the other way

For biggest first, add reverse=True inside the brackets. It works the same for sorted and for sort.

This "hand it over by name" way of writing is covered properly in chapter 3, so for now just take the shape as it stands.

scores = [80, 45, 95]print(sorted(scores, reverse=True))

Result

[95, 80, 45]

06 / 07

Text sorts too

Text sorts as well, and with plain small letters it comes out in alphabetical order.

Strictly it is ordering by the number each character was given, so mixing in capitals can surprise you: every capital comes before every small letter. Keep to one case and you will not be caught out.

fruits = ["orange", "apple", "banana"]print(sorted(fruits))

Result

['apple', 'banana', 'orange']

07 / 07

Which to use

  • want to keep the original … ordered = sorted(scores)
  • happy to sort it in place … scores.sort()

When in doubt, pick sorted. Nothing of yours gets broken, which makes it the safer choice.

Next you learn to cut just a part out of something that is in a row.