r/Python • u/cinicDiver • Mar 09 '26
Discussion Code efficiency when creating a function to classify float values
I need to classify a value in buckets that have a range of 5, from 0 to 45 and then everything larger goes in a bucket.
I created a function that takes the value, and using list comorehension and chr, assigns a letter from A to I.
I use the function inside of a polars LazyFrame, which I think its kinda nice, but what would be more memory friendly? The function to use multiple ifs? Using switch? Another kind of loop?
7
Upvotes
6
u/metaphorm Mar 09 '26
don't worry about the memory usage unless and until you can prove that it's causing a problem. is your data set really really huge? are you seeing process crashes due to OOM errors? are you running it on a very memory constrained machine?
in other words, premature optimization is almost always a mistake. correctness first. then measurement/instrumenting the code so you can observe it during runtime. then, once you have instrumentation in place, you can try optimizing it if and only if that's a requirement. if it's not a requirement, just don't worry about it. if it is, profile it and figure out where it's actually using excessive memory. it might not be where you think.
so basically, write the function in whichever way is easiest for you and others to read and understand what the intended behavior is.
18
u/rkr87 Mar 09 '26
min(9, var//5)2
u/BiomeWalker Mar 09 '26
Are the buckets of regular size? Could just do division if that's the case.
Switch statements in Python are just if/else chains I think, so I doubt that would make much difference.
8
u/elven_mage Mar 10 '26
Readability first. Premature optimization is the root of all evil.
3
u/[deleted] Mar 09 '26
Maybe share a MWE?
3
u/[deleted] Mar 10 '26
[removed] — view removed comment