Reputation:
sum_num = 0
for human in humans:
sum_num += human.limbs
return sum_num
Assume object human
has a attribute limbs
as in:
human.limbs = rand.int(0, 4)
What would be a good way to shorten this as we would with list comprehension?
sum_num = sum_num + human.limbs for human in humans
Obviously, the above raises an error. Is there no way to shorten some for loop like above?
Upvotes: 1
Views: 248
Reputation: 49862
The sum
function is the Pythonic way to sum. sum()
takes an iterable. In this case, a very helpful iterable is the generator expression. Generator expressions use (basically) the same syntax as list comprehensions. Using sum()
and a generator expression, what you are trying to do, can be expressed, quite simply, as:
sum(human.limbs for human in humans)
Upvotes: 3