Python list + list vs. list.append()

后端 未结 2 513
野性不改
野性不改 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

提交回复
热议问题