Today I spent about 20 minutes trying to figure out why this worked as expected:
users_stories_dict[a] = s + [b]
but this would have a None
value:
users_stories_dict[a] = s.append(b)
Anyone know why the append function does not return the new list? I'm looking for some sort of sensible reason this decision was made; it looks like a Python novice gotcha to me right now.
append() adds a single element to the end of the list while . extend() can add multiple individual elements to the end of the list.
In general case append will add one item to the list, while += will copy all elements of right-hand-side list into the left-hand-side list.
Python append() method adds an element to a list, and the extend() method concatenates the first list with another list (or another iterable). When append() method adds its argument as a single element to the end of a list, the length of the list itself will increase by one.
append() that you can use to add items to the end of a given list. This method is widely used either to add a single item to the end of a list or to populate a list using a for loop. Learning how to use . append() will help you process lists in your programs.
append
works by actually modifying a list, and so all the magic is in side-effects. Accordingly, the result returned by append
is None. In other words, what one wants is:
s.append(b)
and then:
users_stories_dict[a] = s
But, you've already figured that much out. As to why it was done this way, while I don't really know, my guess is that it might have something to do with a 0
(or false
) exit value indicating that an operation proceeded normally, and by returning None
for functions whose role is to modify their arguments in-place you report that the modification succeeded.
But I agree that it would be nice if it returned the modified list back. At least, Python's behavior is consistent across all such functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With