79535054

Date: 2025-03-25 23:21:00
Score: 0.5
Natty:
Report link

You can use the walrus operator := to specify how the value changes with each iteration inside the list comprehension, to achieve the following:

a = [1, 2, 20, 3, 30, 300]
count = 0
b = [sum(a[count:(count := count + i)]) for i in range(1,4)]
print(b)

This should give you

[1, 22, 333]

Which is the desired outcome.

Edit: Apparently walrus operator is a really controversial feature in python that a lot of people hate it because it goes against a lot of Zen of Python rules. So I guess use it with caution?

Reasons:
  • Whitelisted phrase (-1.5): You can use
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • Low reputation (1):
Posted by: Dawith Lim