Analysis of Python list operation code instance


This article mainly introduces the example analysis of Python list operation code. The example code is introduced in detail in this article, which has certain reference value for your study or work. You can refer to the following for your friends

When operating the list, we often use the operation operations on the list, such as adding and deleting the list. In fact, we often encounter such a problem that the list operation is easy to be confused.

Someone has made a summary, which is very clear, so I will not elaborate more:

1. Append() appends a new element to the end of the list. The list occupies only one index bit and is added to the original list

2. Extend() appends a list to the end of the list, appends every element in the list, and adds it to the original list

3. + using the + sign directly looks the same as using extend(), but it actually generates a new list to store the sum of the two lists, which can only be used on the addition of the two lists

4. + = the effect is the same as extend(), append a new element to the original list and add it to the original list

There is also a problem in this, that is, how to add and subtract the list. Many people are easy to use the + – sign to add and subtract directly, which is easy to make mistakes. In fact, there are other operation methods for addition and subtraction:

I wrote an example that can clearly explain several differences and similarities and differences, as follows:

import numpy as np

left = []
right = []

data1 = [12,12,12,12,12,12,12]
data2 = [12,12,12,12,12,12,12]
data3 = []
for item in data1:

for item1 in data2:

aleft = np.array(left)
bleft = np.array(right)

cleft = aleft - bleft
dleft = aleft + bleft
print("list a sub list b:")
print("list a add list b:")
print("list a append list b:")
cleft = data1 + data2
print("list a extend list b:")


list a sub list b:
[0 0 0 0 0 0 0]
list a add list b:
[24 24 24 24 24 24 24]
list a append list b:
[12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12]
[12, 12, 12, 12, 12, 12, 12, [12, 12, 12, 12, 12, 12, 12]]
list a extend list b:
[12, 12, 12, 12, 12, 12, 12]

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.