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?
18
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.
0
u/cinicDiver Mar 09 '26
Yes, buckets have a range of 5 until the last, 0-4.99, 5-9.99, etc. Until 45, everything greater belongs to the same bucket.
6
u/BiomeWalker Mar 09 '26
Then division should be your answer I think.
Divide by 5, cast to int -> that's the bucket
8
3
3
Mar 10 '26
[removed] — view removed comment
1
u/cinicDiver Mar 10 '26
Yeah! Actually that's what I found at the end, I changed my function for a mix of division with floor and clip.
I thought of the when chain, but it was too long and would make the code weird, so I thought there would be something better.
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.