 # FAQ: Code Challenge: Lists - Append Sum

Is the return where you really want it?

Hello all,

So I know this is not simplified code, but it worked! Codeacademy has not taught us while loops or for loops yet, but I know they exist. How could I simplify this code?

def append_sum(lst):
y=lst[-2]
z=lst[-1]
#print(y)
#print(z)
a=z+y
lst.append(a)
print(lst)
y=lst[-2]
z=lst[-1]
#print(y)
#print(z)
a=z+y
lst.append(a)
print(lst)
y=lst[-2]
z=lst[-1]
#print(y)
#print(z)
a=z+y
lst.append(a)
return lst

#Uncomment the line below when your function is done
print(append_sum([1, 1, 2]))

You could replace some variables with their definitions, you’re only using them once, don’t need to name them.

2 Likes

Ionatan,

Do you mean set my variables inside of definitions and then call the definitions?

Thanks!

if you have `a = 1` then you can replace all uses of `a` with `1`, and if you’re then no longer using a then you can remove it

I used this solution as well, yes:

``````def append_sum(lst):
for i in range(3):
sum = lst[-1] + lst[-2]
lst.append(sum)
return lst

#Uncomment the line below when your function is done
print(append_sum([1, 1, 2]))
``````
``````def append_sum(lst):
one = lst[-1] + lst[-2]
lst.append(one)
two = lst[-1] + lst[-2]
lst.append(two)
three = lst[-1] + lst[-2]
lst.append(three)
return lst
``````

This is my simple code. I should go learn loop!

This is my code, just change how many .appends you want to ‘lst’ to ‘len(lst)+3’. Works fine #Make it follow the length of the list:
def append_sum(lst):
n = len(lst)
while n > 0:
result = sum(lst[-2:])
lst.append(result)
n = n-1
return lst