Python list + list vs. list.append()

后端 未结 2 501
野性不改
野性不改 2020-12-03 16:22

Today I spent about 20 minutes trying to figure out why this worked as expected:

users_stories_dict[a] = s + [b] 

but this would have a

相关标签:
2条回答
  • 2020-12-03 16:24

    The append() method returns a None, because it modifies the list it self by adding the object appended as an element, while the + operator concatenates the two lists and return the resulting list

    eg:

    a = [1,2,3,4,5]
    b = [6,7,8,9,0]
    
    print a+b         # returns a list made by concatenating the lists a and b
    >>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
    
    print a.append(b) # Adds the list b as element at the end of the list a and returns None
    >>> None
    
    print a           # the list a was modified during the last append call and has the list b as last element
    >>> [1, 2, 3, 4, 5, [6, 7, 8, 9, 0]]
    

    So as you can see the easiest way is just to add the two lists together as even if you append the list b to a using append() you will not get the result you want without additional work

    0 讨论(0)
  • 2020-12-03 16:26

    append works by actually modifying a list, and so all the magic is in side-effects. Accordingly, the result returned by append is None. In other words, what one wants is:

    s.append(b)

    and then:

    users_stories_dict[a] = s

    But, you've already figured that much out. As to why it was done this way, while I don't really know, my guess is that it might have something to do with a 0 (or false) exit value indicating that an operation proceeded normally, and by returning None for functions whose role is to modify their arguments in-place you report that the modification succeeded.

    But I agree that it would be nice if it returned the modified list back. At least, Python's behavior is consistent across all such functions.

    0 讨论(0)
提交回复
热议问题