🎓 A1Learner
🔍
0 of 116 lessons completed

Python Sort Lists

Sorting a list puts its items in order. Scores and names are common items to sort.

Sort a list in place

sort() changes the list itself.

nums = [5, 2, 9, 1]
nums.sort()
print(nums)

Keep the old list with sorted()

sorted() returns a new list. The old list stays as it was.

nums = [5, 2, 9, 1]
ordered = sorted(nums)
print(ordered)
print(nums)

Sort from big to small

Add reverse=True inside the round brackets.

scores = [72, 95, 88]
scores.sort(reverse=True)
print(scores)

Sort text fairly

key=str.lower compares the lower-case forms. Capitals then stop jumping ahead.

names = ["cherry", "Banana", "apple"]
print(sorted(names))
print(sorted(names, key=str.lower))

Flip the order with reverse()

reverse() does not sort. It just turns the list around.

letters = ["a", "b", "c"]
letters.reverse()
print(letters)

Example

scores = [72, 95, 88, 60]
scores.sort(reverse=True)
print(scores)
names = ["Zoe", "adam", "Mia", "bob"]
names.sort(key=str.lower)
print(names)

Key points

  • Use sort() to sort a list in place
  • Use sorted() to get a new sorted list and keep the old one
  • Use reverse=True to sort from big to small
  • Key: a rule Python uses to compare items while sorting
  • Use reverse() to flip the current order without sorting
  • Sorting puts the items of a list in order.
  • Use key=str.lower for a fair text sort.

In this example, scores starts out of order. sort(reverse=True) puts the biggest score first. print(scores) shows the scores from high to low. names then holds four names with mixed capitals. sort(key=str.lower) compares the lower-case forms of the names. print(names) shows the names in fair alphabetical order.

Note

Text sorts by character codes, so capital letters come before small letters.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

You need a sorted copy, and the old list must stay unchanged. Which code does that?