0

I want to make a loop, that sums up the first two items of a list, and stores the result in a new list. After that it should take the first three items of the first list and sum up these and store the result in the same list aswell.

What I try to do:

x = [1, 2, 3, 4]
y = []

for i in x:
     s = i + (i+1)
     y.append(s)

This does not work at all. Because of my bad understanding its hard to get help from google. I hope some might understand my problem.

4
  • 1
    y = [sum(x[:i]) for i in (2, 3)] or y = [sum(x[:2]), sum(x[:3])] Commented Apr 13, 2020 at 15:38
  • In your loop, i is not an index, it's the value from the list. Commented Apr 13, 2020 at 15:38
  • When you are doing i +(i +1) it's not sums the first tow elements you can do it with enumerat of the list and by the index get the second element Commented Apr 13, 2020 at 15:38
  • First of all thanks to your fast responses. @StevenRumbalski I tried both of your versions. Can i somehow change the code that i do not have to tipe in every Index of the List? I need this for Lists that are much bigger than the text version. Commented Apr 13, 2020 at 15:52

3 Answers 3

2

This will work for you

x = [1, 2, 3, 4]
y = []

for i in range(2,len(x)+1):
    y.append(sum(x[:i]))
print(y)
Sign up to request clarification or add additional context in comments.

Comments

0

Looks like you want a list comprehension that sums incrementally larger and larger lists as you iterate through


This will work.

>>> x = [1,2,3,4]
>>> x
[1,2,3,4]

# Note we put the condition `if i != 0` so that we ignore the first entry in the list
#
# This comprehension essentially is taking the indices for the given list
# and utilizing the indices to generate a subset list of indices (`range(i+1)`)
# and by using these subset indices we can generate a subset of values which
# we can then sum as you requested.
>>> y = [sum([x[idx] for idx in range(i+1)]) for i in range(len(x)) if i !=0]
>>> y
[3, 6, 10]

Let me know if you have any questions!

Comments

0

You don't really need a loop but if you want:

x = [1, 2, 3, 4]
new_list = []

for count in range(len(x) - 2):
  if count <2:
    new_list.append( sum(x[:count+2]) )

print(new_list)

# OR without loop 

x = [1, 2, 3, 4]
new_list = []

sums_of_the_first_two = sum(x[:2])
new_list.append(sums_of_the_first_two)
sums_of_the_first_three = sum(x[:3])
new_list.append(sums_of_the_first_three)

print(new_list)

Edit: The 2nd part in the comment of Steven Rumbalski is the best solution i think

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.