Answer a question

I'm trying my hand at converting the following loop to a comprehension.

Problem is given an input_list = [1, 2, 3, 4, 5] return a list with each element as multiple of all elements till that index starting from left to right.

Hence return list would be [1, 2, 6, 24, 120].

The normal loop I have (and it's working):

l2r = list()
for i in range(lst_len):
    if i == 0:
        l2r.append(lst_num[i])
    else:
        l2r.append(lst_num[i] * l2r[i-1])

Answers

Python 3.8+ solution:

  • := Assignment Expressions
lst = [1, 2, 3, 4, 5]

curr = 1
out = [(curr:=curr*v) for v in lst]
print(out)

Prints:

[1, 2, 6, 24, 120]

Other solution (with itertools.accumulate):

from itertools import accumulate

out = [*accumulate(lst, lambda a, b: a*b)]
print(out)
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐