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
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.
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
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.