[].append(x) behaviour

后端 未结 4 745
北荒
北荒 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 08:21

    The method list.append() changes the list inplace, and returns no result (so returns None if you prefer)

    Many methods of list work on the list inplace, so you doesn't need to reassign a new list to override the old one.

    >>> lst = []
    >>> id(lst)
    4294245644L
    >>> lst.append(1)
    >>> id(lst)
    4294245644L   # <-- same object, doesn't change.
    

    With [].append(1), you're adding 1 to a list freshly created, and you have no reference on this one. So once the append is done, you have lost the list (and will be collected by the garbage collector).
    By the way, fun fact, to make sense to my answer:

    >>> id([].append(1))
    1852276280
    >>> id(None)
    1852276280
    

提交回复
热议问题