1

I'm quite new to Python and trying to do something but cannot figure out how...

x = 20
list = [5, 3, 7]

I want to create a loop that add the previous element from the list to x

Loop 1 : result = 20+0 = 20 (no previous element)

Loop 2 : result = 20+5 = 25

Loop 3 : result = 20+5+3 = 28

So at the end result should look like that : result = [20, 25, 28]

Any idea how I could achieve this result ?

Thank you for your help!

2
  • 1
    Is your x, 10 or 20? Commented Jun 14, 2020 at 17:07
  • 20 (I edited the post) Commented Jun 14, 2020 at 17:09

3 Answers 3

1

Here's how I'd do it:

>>> x = 10
>>> my_list = [5, 3, 7]
>>> [x + sum(my_list[:n]) for n in range(len(my_list))]
[10, 15, 18]

Note that naming a list list is a bad idea because it overwrites the builtin list function!

Sign up to request clarification or add additional context in comments.

Comments

0

Try it:

x = 20
my_list = [5, 3, 7]
result = [x]
for i in range(len(my_list)-1):
    x += my_list[i]
    result.append(x)
print(result)

Comments

0

You can use a list comprehension:

x = 20
lst = [5, 3, 7]
lst = [x+sum([lst[i] for i in range(i)]) if i else x for i,n in enumerate(lst)]
print(lst)

Output:

[20, 25, 28]

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.