sort() and sorted()
list.sort() versus sorted(list)
sort() changes the list and returns None. sorted() works on any iterable and returns a new list.
a = [3, 1, 2]
b = sorted(a)
print(a, b)
a.sort()
print(a)
print(a.sort())
Output:
[3, 1, 2] [1, 2, 3]
[1, 2, 3]
None
key=
Sort by a calculated value. The function is called once for each item.
words = ["banana", "kiwi", "apple", "fig"]
print(sorted(words, key=len))
print(sorted(words, key=lambda w: w[-1]))
print(sorted(["b", "A", "c", "B"], key=str.lower))
Output:
['fig', 'kiwi', 'apple', 'banana']
['banana', 'apple', 'fig', 'kiwi']
['A', 'b', 'B', 'c']
reverse=True and reverse()
Sort from largest to smallest. list.reverse() just flips the current order.
n = [5, 2, 9]
print(sorted(n, reverse=True))
n.reverse()
print(n)
Output:
[9, 5, 2]
[9, 2, 5]
Sorting by several things
A key can return a tuple: Python compares the first item, then the second on ties. Use a minus sign to reverse one number.
students = [("Ram", 80), ("Sita", 90), ("Hari", 80), ("Gita", 90)]
best_first = sorted(students, key=lambda s: (-s[1], s[0]))
print(best_first)
Output:
[('Gita', 90), ('Sita', 90), ('Hari', 80), ('Ram', 80)]
operator.itemgetter / attrgetter
A faster, clearer alternative to a small lambda.
from operator import itemgetter
rows = [{"n": "Ram", "m": 70}, {"n": "Sita", "m": 95}]
print(sorted(rows, key=itemgetter("m"), reverse=True))
Output:
[{'n': 'Sita', 'm': 95}, {'n': 'Ram', 'm': 70}]
Python's sort is stable: items that compare equal keep their original order. So you can sort twice, first by the minor key and then by the major key.
List comprehensions
A comprehension builds a list in one expression: [expression for item in iterable if condition].
[x for x in ...]
Transform every item.
print([n * n for n in range(1, 6)])
print([w.upper() for w in ["a", "b"]])
Output:
[1, 4, 9, 16, 25]
['A', 'B']
[... if condition]
Keep only some items.
print([n for n in range(20) if n % 3 == 0])
print([w for w in ["fig", "apple", "kiwi"] if len(w) > 3])
Output:
[0, 3, 6, 9, 12, 15, 18]
['apple', 'kiwi']
[a if cond else b for ...]
Choose a value for each item.
print(["even" if n % 2 == 0 else "odd" for n in range(5)])
Output:
['even', 'odd', 'even', 'odd', 'even']
Two loops in one comprehension
The left loop is the outer loop. Good for flattening or making pairs.
matrix = [[1, 2], [3, 4], [5, 6]]
print([x for row in matrix for x in row])
print([(a, b) for a in "ab" for b in (1, 2)])
Output:
[1, 2, 3, 4, 5, 6]
[('a', 1), ('a', 2), ('b', 1), ('b', 2)]
Set and dict comprehensions
The same idea with { }.
print({len(w) for w in ["a", "bb", "cc", "d"]})
print({w: len(w) for w in ["red", "green"]})
Output:
{1, 2}
{'red': 3, 'green': 5}
Generator expressions
Round brackets: items are produced one at a time, so no big list is built. Ideal inside sum, any, max.
print(sum(n * n for n in range(1, 101)))
print(any(c.isdigit() for c in "abc7"))
Output:
338350
True
Finding things
min/max with key, and next()
Find the best item, or the first item matching a rule.
people = [("Ram", 17), ("Sita", 21), ("Hari", 19)]
print(max(people, key=lambda p: p[1]))
print(next(p for p in people if p[1] > 18))
print(next((p for p in people if p[1] > 99), "nobody"))
Output:
('Sita', 21)
('Sita', 21)
nobody
Try it yourself
- Sort a list of words by length, and by alphabet when the length is the same.
- Use a comprehension to make the squares of only the odd numbers up to 20.
- Flatten [[1], [2, 3], [4]] with one comprehension.
Next lesson: tuples and sets.

Comments
Loading comments…