Differences between append and + in Python list, pythonappend
When using a list in python, you often need to add an element to a list, as shown in the following two usage methods:
Copy codeThe Code is as follows:
T = [1, 2, 3]
T1 = t. append ([4])
T2 = t + [4]
The above two usage methods are different. Let's take a look at the actual running results:
Copy codeThe Code is as follows:
>>> 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]
We can see that after t. append ([4]) is used, it is actually added in the t list, not as expected in t1, and t1 is None at this time.
After t2 = t + [4] is used, t2 adds an element 4 on the basis of the original t1, while the elements in the actual list t remain unchanged.
Conclusion:
Using append is actually to modify a list, and using + is actually to create a new list.