Python list extension and variable assignment

2019-02-19 12:49发布

问题:

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?

回答1:

Because, as you noticed, the return value of extend is None. This is common in the Python standard library; destructive operations return None, 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 sort method on lists returns None as well, while the non-destructive sorted function returns a value.



回答2:

Because all the in-place functions return None, to emphasize the fact that they're mutating their argument. Otherwise, you might assign the return value to something, not realising that the argument had also changed.



回答3:

Simply .extend() returns none

If u want you can join them as such;

a= a+b