Jan-23-2023, 04:23 AM
(This post was last modified: Jan-23-2023, 04:23 AM by deanhystad.)
Since reading this thread I've been looking for an example where reduce was a better choice than any other python construct. I did not fine any. Every example I found for reduce() could be written shorter and clearer using a comprehension.
from functools import reduce from time import time values = [('A', b) for b in range(10000000)] start = time() print(reduce(lambda a, b: a + b[1], values, 0)) print(time() - start) start = time() print(sum((value[1] for value in values))) print(time() - start)
Output:49999995000000
0.7833819389343262
49999995000000
0.7230224609375
The comprehension is even a tiny bit faster.