Search code examples
pythonlist-comprehensionnested-loops

Python list comprehension for the given code


Can I use list comprehension or reduce a for loop for the code?

x=[100,200,300]
y=[10,20,50,70,80]
results=[]
for i in range(len(x)):
    temp=[]
    for j in range(len(y)):
        x[i]+=y[j]
        temp.append(x[i])
    results.append(temp)
print(results)

Solution

  • Python 3.8 added a neat feature of assignment expressions which is really handy in producing cumulative sums, and can help you replace these loops in a couple of list comprehensions:

    total = 0
    cumsums = [total := total + t for t in y]
    result = [[c+s for c in cumsums]  for s in x]