Aral Code

Collections Lesson 15 of 23

Python List Methods, Sorting and List Comprehensions

Sort lists with sort() and sorted(), reverse them, sort by a key, and create new lists in one line with list comprehensions.

Now that you can create and change lists, let's learn how to sort them, process them quickly, and build new lists in a single, elegant line with list comprehensions.

sort() and sorted()

grades = [88, 72, 95, 60, 81]

grades.sort()                 # changes the list itself
print(grades)

grades.sort(reverse=True)     # highest first
print(grades)

Output

[60, 72, 81, 88, 95]
[95, 88, 81, 72, 60]

sorted() returns a new sorted list and leaves the original alone:

names = ["Carla", "ana", "Ben"]
print(sorted(names))
print(sorted(names, key=str.lower))   # ignore capital letters
print(names)

Output

['Ben', 'Carla', 'ana']
['ana', 'Ben', 'Carla']
['Carla', 'ana', 'Ben']

By default, uppercase letters come before lowercase ones. key=str.lower sorts as if everything were lowercase.

Sorting by a key

key tells Python what to sort by. Here we sort words by their length:

places = ["Cebu", "Puerto Princesa", "Iloilo", "Vigan"]
print(sorted(places, key=len))

Output

['Cebu', 'Vigan', 'Iloilo', 'Puerto Princesa']

For a list of pairs, a lambda (a tiny one-line function) picks the part to sort by:

scores = [("Ana", 92), ("Ben", 85), ("Carla", 97)]
ranked = sorted(scores, key=lambda s: s[1], reverse=True)
for name, score in ranked:
    print(name, score)

Output

Carla 97
Ana 92
Ben 85

reverse()

countdown = [1, 2, 3, 4, 5]
countdown.reverse()
print(countdown)
print(countdown[::-1])   # reversed copy using slicing

Output

[5, 4, 3, 2, 1]
[1, 2, 3, 4, 5]

List comprehensions

A list comprehension builds a new list from another in one line. This loop:

prices = [100, 250, 40]
with_vat = []
for p in prices:
    with_vat.append(p * 1.12)

…can be written as:

prices = [100, 250, 40]
with_vat = [p * 1.12 for p in prices]
print(with_vat)

Output

[112.00000000000001, 280.0, 44.800000000000004]

Read it as: "make a list of p * 1.12 for each p in prices". (Use round(p * 1.12, 2) to clean up the decimals.)

With a condition

Add if at the end to keep only some items:

grades = [88, 72, 95, 60, 81]
passing = [g for g in grades if g >= 75]
print(passing)

names = ["ana", "ben", "carla"]
print([n.title() for n in names])

squares = [n ** 2 for n in range(1, 6)]
print(squares)

Output

[88, 95, 81]
['Ana', 'Ben', 'Carla']
[1, 4, 9, 16, 25]

Useful functions for lists

FunctionExampleResult
len()len([4, 8, 1])3
sum()sum([4, 8, 1])13
max() / min()max([4, 8, 1])8
any()any(g < 75 for g in grades)True if at least one fails
all()all(g >= 75 for g in grades)True if everyone passed

Example: class statistics

grades = [88, 72, 95, 60, 81, 90, 77]

passing = [g for g in grades if g >= 75]
top3 = sorted(grades, reverse=True)[:3]

print("Class average:", round(sum(grades) / len(grades), 1))
print("Passing rate:", f"{len(passing) / len(grades):.0%}")
print("Top 3:", top3)
print("Everyone passed?", all(g >= 75 for g in grades))

Output

Class average: 80.4
Passing rate: 71%
Top 3: [95, 90, 88]
Everyone passed? False

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. What does grades.sort() return?
2. How do you sort from highest to lowest?
3. What does [x * 2 for x in [1, 2, 3]] produce?
4. What does [n for n in range(10) if n % 2 == 0] produce?

By Sir Reyel · Last updated 2026-12-04