0

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)
2
  • x isn't defined in the snippet you shared. Commented Aug 29, 2020 at 17:01
  • I'm sorry sir, I've added x now! Commented Aug 29, 2020 at 18:19

1 Answer 1

3

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.