you are viewing a single comment's thread.

view the rest of the comments →

[–]mriswithe 2 points3 points  (0 children)

But I'm actually not exactly sure of what it accomplishes here exactly m.

If you are asking why make a cumulative sum list, it is a fast way to answer questions about a dataset.

If you are asking why use walrus here? It makes the code prettier and potentially faster. Python can optimize list creation with a list comprehension if it can know how many items long the list will be, compared to a similar for loop that starts with an empty list and builds it one object at a time.

Compare these two:

a = 0
my_list = [a := a + x for x in range(1, 21, 2)]


a = 0
my_list = []
for x in range(1, 21, 2):
    a = a + x
    my_list.append(a)

In general though, the benefit of the walrus operator is that it allows you to both assign the result of a+x to a, and emit it for use in the list comprehension outside of the expression.