Loops comprehension

I have this list:
list = [1, 5, 4, 6, 3]
I want to do:
1+5+4, 5+4+6, 4+6+3
and store the different values in another list

How can I do that?

You could do something like this

list = [1, 5, 4, 6, 3]
newlist = []

for i in range(0, len(list) - 2):
    print(i)
    newlist.append(list[i] + list[i+1] + list[i+2])

print(newlist)
# prints [10, 15, 13]

and that would do the job.

3 Likes

You could also use a list comprehension for brevity :

lst = [1, 5, 4, 6, 3]
new_list= [lst[index] + lst[index+1] + lst[index+2] for index in range(len(lst) - 2)]