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/Published at
2024-11-27 02:08:00 UTCEvent JSON
{
"id": "20f053f404a269887e9bcb376de23607eea7237721d945ec0f2ad277d22c8394",
"pubkey": "7e9159fbfd5526415c8d2de2e4c7654e3660883f9ccae720a70fa3c1f3cf1f45",
"created_at": 1732673280,
"kind": 1,
"tags": [
[
"proxy",
"https://mastodon.social/@treyhunner/113552476108081829",
"web"
],
[
"t",
"python"
],
[
"proxy",
"https://mastodon.social/users/treyhunner/statuses/113552476108081829",
"activitypub"
],
[
"L",
"pink.momostr"
],
[
"l",
"pink.momostr.activitypub:https://mastodon.social/users/treyhunner/statuses/113552476108081829",
"pink.momostr"
],
[
"-"
]
],
"content": "Avoid unnecessary sorting in Python.\n\n❌ Instead of this:\nsmallest = sorted(items)[0]\n\n✅ Do this:\nsmallest = min(items)\n\n❌ Instead of this:\nsmallest = sorted(items)[:3]\n\n✅ Do this:\nimport heapq\nsmallest = heapq.nsmallest(3, items)\n\nWhy avoid sorting?\n\n1. Performance: min is O(n), nsmallest is O(n log k), sorted is O(n log n)\n2. Readability: min \u0026 nsmallest note what we really want our code to do\n\nFor more on the performance of various operations in #Python, see https://pym.dev/time-complexities/",
"sig": "37a686d1d5417ed81d8549ee63d3eaa1ba298308ab809055004c723c1ca78a299fa9f1073da433bbf34aa918c5b88732458f6597e3460f6c0800c767ad4ee9b0"
}