A brief analysis of the difference between Python list append and +

  • 2020-04-02 14:34:31
  • OfStack

When using lists in python, you often need to add an element to a list. For example, the following two usage methods need to be noted:


t = [1, 2, 3]
t1 = t.append([4])
t2 = t + [4]

The above two usage methods are different, let's see the actual operation effect:


>>> t = [1, 2, 3]
>>> t1 = t.append([4])
>>> t
[1, 2, 3, [4]]
>>> t1
>>>
>>> t2 = t + [4]
>>> t2
[1, 2, 3, [4], 4]
>>> t
[1, 2, 3, [4]]

You can see that after using t.apend ([4]), it actually increases in the list of t, not t1 as we expected, and t1 is None.

When t2 = t + [4] is used, t2 adds another element 4 to the original t1, while the element in the actual list t does not change.

Conclusion:

Using append is actually modifying a list, and using + is actually creating a new list.


Related articles: