Python Code Challenges: Lists - 1. Append Sum Attempting to Answer w/ Recursion; Teach Me!

Challenge Question:
Write a function named append_sum that has one parameter — a list named named lst .

The function should add the last two elements of lst together and append the result to lst . It should do this process three times and then return lst .

For example, if lst started as [1, 1, 2] , the final result should be [1, 1, 2, 3, 5, 8] .

My Code:

def append_sum(lst):
if(len(lst) >= 6):
return list(lst)
else:
lst.append(list(lst[-2]+lst[-1]))
append_sum(lst)

Question/Help:
So obviously I don’t have to answer the question this way, but I saw that maybe it can be done with recursion, plus also trying to learn recursion in practice. So it might be that my understanding of recursion is still not on point, but also because python is this weird alien language to me.

So my problem is most likely with the else statement. Originally if the else statement was a single line of:

lst.append(list[-2] + lst[-1])

the code runs fine-ish. It returns None. Which I’m also trying to wrap my head around. But after adding append_sum(lst), I get:

Traceback (most recent call last):
File “script.py”, line 11, in
print(append_sum([1, 1, 2])) //print test curtesy of the challenge question
File “script.py”, line 7, in append_sum
lst.append(list(lst[-2]+lst[-1]))
TypeError: ‘int’ object is not iterable

For me, the important thing is that I understand the code. So it’d be helpful if someone could explain both the “None” result and the current “TypeError” to me, and how I can improve on/fix the recursion.

Hello @emmav171, welcome to the forums! The None is a result of you function not returning anything. The TypeError is caused because you are trying to turn an integer into a list-which doesn’t work, since and integer can’t be iterated over. Consider this code:

a = 1
for i in a:
  print(i)

What is i going to be? What is something that is part of 1 that isn’t 1? As general rule of thumb, if you couldn’t create a for loop using that object, you won’t be able to turn it into a list using list().

I hope this helps!


Also, to help you further, I need to know how you got your code. Why is this in your code:

And the list() here-why have you put it there:

if(len(lst) >= 6):
return list(lst)

It was to check the length of the list. I now realized it doesn’t work if it continuously appends…

As for the list in

lst.append(list(lst[-2]+lst[-1]))

it was because it gave me an error

Looking back on the question, this method would have thrown it into an infinite loop.

Thanks for the feedback, definitely expanded my knowledge. Just doesn’t explain why is python so alien tho lol

1 Like