6 ms·
The best one would be: total = sum(map(f, data)) Not only does it take less resources as it only has to loop once because map creates a generator. This is abs
by red1reaper 2y ago
The best one would be:
total = sum(map(f, data))
Not only does it take less resources as it only has to loop once because map creates a generator. This is absolutly the use case of map, if you want to apply the same function, which is already defined, to all members of a list/iterator, map is the correct tool for the job. Now if you wanted to apply a transformation that is not in a function there would be an argument to use a comprehension as it would be better than using an inline lambda in a map. But if you already have the method you want to apply, just use map() and then pass that to sum()
- Izkata 2y agoA generator expression would also avoid looping twice - this is valid python: total = sum(f(record) for record in housing_records)