How are these return statements different

Question:

Take these two sample code statments:

result = []
return result.append(feed.entries[0])

&

result = []
result.append(feed.entries[0])
return result

The first gives me an error because the method that result is passed to complains of a NonType not being iterable. Why is this? To me both statements are equivalent

Asked By: timebandit

||

Answers:

The append method of a list does not return anything

>>> a = []
>>> type(a.append(12))
<type 'NoneType'>

So when you’re doing:

return result.append(feed.entries[0])

You’re actually returning None in all cases, whereas when you do:

result.append(....)
return result

you’re returning the list after it has been mutated (modified) hence giving a the expected result.

Answered By: Ketouem
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.