[].append(x) behaviour

后端 未结 4 746
北荒
北荒 2021-01-23 07:21

This executes as I\'d expect:

>>>x=[]
>>>x.append(3)
>>>x
[3]

Why does the following return None?

&g         


        
4条回答
  •  醉酒成梦
    2021-01-23 07:58

    because list.append changes the list itself and returns None ;)

    You can use help to see the docstring of a function or method:

    In [11]: help(list.append)
    Help on method_descriptor:
    
    append(...)
        L.append(object) -- append object to end
    

    EDIT:

    This is explained in docs of python3:

    Some collection classes are mutable. The methods that add, subtract, or rearrange their members in place, and don’t return a specific item, never return the collection instance itself but None.

提交回复
热议问题