Python list extension and variable assignment

心已入冬 提交于 2019-12-01 08:54:13

问题


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



来源:https://stackoverflow.com/questions/9724356/python-list-extension-and-variable-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!