Python list + list vs. list.append()

Posted on

Question :

Python list + list vs. list.append()

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.

Answer #1:

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.

Answer #2:

The append() method returns a None, because it modifies the list it self by adding the object appended as an element, while the + operator concatenates the two lists and return the resulting list

eg:

a = [1,2,3,4,5]
b = [6,7,8,9,0]

print a+b         # returns a list made by concatenating the lists a and b
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

print a.append(b) # Adds the list b as element at the end of the list a and returns None
>>> None

print a           # the list a was modified during the last append call and has the list b as last element
>>> [1, 2, 3, 4, 5, [6, 7, 8, 9, 0]]

So as you can see the easiest way is just to add the two lists together as even if you append the list b to a using append() you will not get the result you want without additional work

Answered By: P2bM

Leave a Reply

Your email address will not be published. Required fields are marked *