Sum Comprehension
Documentation Index
Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt
Use this file to discover all available pages before exploring further.
Sourcery refactoring id: sum-comprehension
Section titled “Sourcery refactoring id: sum-comprehension”Description:
Section titled “Description:”Replaces summed values created with for loops with sum comprehensions
Before:
Section titled “Before:”total = 0for hat in hats: total += hat.priceAfter:
Section titled “After:”total = sum(hat.price for hat in hats)Explanation:
Section titled “Explanation:”Much of programming is about adding up lists of things, and Python has the
built-in sum() function to help with this.
This is much shorter, which is a definite bonus. The code also now explicitly tells you what it is trying to do - sum the price of all the hats.