r/learnpython • u/lehmagavan • Sep 26 '26
Parsing large collections of "numeric" strings.
Hi, I'm just a hobbyist and I'm not very familiar with Python ecosystem. I recently came across a specific problem:
I have an iterable (or yield via generator) that contains millions of floating point values, but each one is a Python str, made up example: ["1.987", "0.037389", "1.2", ...]
What's the most efficient way to aggregate them and calculate say, the mean?
I'm writing my own C extension for this and would like to know what to benchmark it against. Couldn't find information on any std way that would avoid calling the float() constructor on each string.
View all comments
Show parent comment
1
u/Expensive-Bear-1376 Sep 27 '26
A potential flaw: list iterators give length hints, and
list(...)makes use of that to allocate the whole memory at once:Output:
And:
Output:
(In my own earlier benchmark, I used generators because of this. I don't have it anymore, might write one again later, as I don't trust benchmarks that first measure one solution and then the other and that's it. I do more repetition/alternation.)