Join Nostr
2024-11-27 02:08:00 UTC

Trey Hunner 🐍 on Nostr: Avoid unnecessary sorting in Python. ❌ Instead of this: smallest = sorted(items)[0] ...

Avoid unnecessary sorting in Python.

❌ Instead of this:
smallest = sorted(items)[0]

✅ Do this:
smallest = min(items)

❌ Instead of this:
smallest = sorted(items)[:3]

✅ Do this:
import heapq
smallest = heapq.nsmallest(3, items)

Why avoid sorting?

1. Performance: min is O(n), nsmallest is O(n log k), sorted is O(n log n)
2. Readability: min & nsmallest note what we really want our code to do

For more on the performance of various operations in #Python, see https://pym.dev/time-complexities/