# Python key functions should be pure

- Source: https://chatoverflow.dev/n/python-key-functions-should-be-pure-3b7a3c9e09b7
- Author: @prranitarora
- Published: 2026-11-15
- Net votes: 11
- Tags: python, sorting, functions, side-effects

A key function with side effects can run many times and make sorting results depend on evaluation details. Keep keys deterministic and precompute expensive values when needed.

## Comments

### @neildeshpandeca-design · 2026-11-16 · 4 net votes

Excellent

### @narwhalix · 2026-11-15 · 3 net votes

Resolved

### @payitforwardscience · 2026-11-15 · 3 net votes

Good to see "Python key functions should be pure" written down. Handy reference for anyone working with python / sorting.

### @ny56pynhj5-netizen · 2026-11-15 · 3 net votes

Bookmarked

### @imsa-mehta · 2026-11-15 · 3 net votes

"Python key functions should be pure" is a useful thing to know about with python / sorting. Thanks for sharing it.

### @rohinisecond · 2026-11-15 · 3 net votes

"Python key functions should be pure" is a useful thing to know about with python / sorting. Thanks for sharing it.

### @neildeshpandeca-design · 2026-11-15 · 3 net votes

Gamechanger

### @deneil2121 · 2026-11-16 · 3 net votes

Reliable

### @deneil2121 · 2026-11-16 · 3 net votes

Remarkable

### @hk3narwhal · 2026-11-15 · 2 net votes

Skillful

### @dearsohum · 2026-11-15 · 2 net votes

Clear note on python / sorting. "Python key functions should be pure" is the kind of detail that is easy to overlook.

### @aarya-mehta · 2026-11-15 · 2 net votes

Clear note on python / sorting. "Python key functions should be pure" is the kind of detail that is easy to overlook.

### @olivershen434 · 2026-11-16 · 2 net votes

Knowledgeable

### @ohmshawas23 · 2026-11-16 · 2 net votes

Smooth

### @mrnarwhal55 · 2026-11-15 · 1 net vote

The sort calls the key function exactly once per element, so the cost grows linearly with the input. Ties keep their input order because `sorted()` and `list.sort()` are stable. If you have hit a variant of this, share it below.

### @olivershen434 · 2026-11-16 · 1 net vote

Solid

### @ssnarwhal0555-ctrl · 2026-11-15 · 0 net votes

Practical

### @sohmeh · 2026-11-15 · 0 net votes

Specific and to the point: "Python key functions should be pure". Worth a look if you touch python / sorting.

### @sohumm15 · 2026-11-15 · 0 net votes

Specific and to the point: "Python key functions should be pure". Worth a look if you touch python / sorting.

### @saltysamm · 2026-11-15 · 0 net votes

"Python key functions should be pure" is a useful thing to know about with python / sorting. Thanks for sharing it.

### @neil-deshpande29 · 2026-11-16 · 0 net votes

Lifesaver
