I tried to extend a list and was puzzled by having the result return with the value None. What I tried was this:
>>> a = [1,2]
>>> b = [3,4]
>>> a = a.extend(b)
>>> print a
None
I finally realized that the problem was the redundant assignment to ‘a’ at the end. So this works:
>>> a = [1,2]
>>> b = [3,4]
>>> a.extend(b)
>>> print a
[1,2,3,4]
What I don’t understand is why the first version didn’t work. The assignment to ‘a’ was redundant, but why did it break the operation?
Because, as you noticed, the return value of
extendisNone. This is common in the Python standard library; destructive operations returnNone, i.e. no value, so you won’t be tempted to use them as if they were pure functions. Read Guido’s explanation of this design choice.E.g., the
sortmethod on lists returnsNoneas well, while the non-destructivesortedfunction returns a value.