News for hackers. Stuff that matters.
Re:GitHub Taught Me to Micromanage by red1reaper on Thursday September 12, 2024 @08:36AM (#41520142)
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()

Re:GitHub Taught Me to Micromanage by Izkata on Thursday September 12, 2024 @08:49PM (#41527146)
A generator expression would also avoid looping twice - this is valid python:

  total = sum(f(record) for record in housing_records)