In Python, there are two ways to add elements to a list: Extend and append. But there are some differences in the use of the two:
1.append You can add a single element, or you can add an iterative object, but extend can only add an iterative object:
arr = [1,2,3,4]in [155]:arr.append (5) in [156]:arrout[156]:[1, 2, 3, 4, 5]in [157]:arr_1= [1,2,3,4]in [158]:arr_1.extend (5)---------------------------------------------------------------------------TypeError Traceback (most recent)<ipython-input-158-a5e15af180e0>inch<module>()----> 1 Arr_1.extend (5) TypeError:'int'Object is notIterable
2. When adding an iterative object, append does not change the type of the added item after it has been added, what type was added before, what type was added, and when extend is added, the added item is iterated, and the elements of the iteration are added to the added array one by one:
Arr_ap = [1,2,3,4= [5,6,7]arr_ap.append (item) in []:arr_apout[]]:[1, 2, 3, 4, [5, 6, 7] In [161= [1,2,3,4= [5,6,7]arr_ex.extend (item) in [162]:arr_exout[162]: [1, 2, 3, 4, 5, 6, 7]
With a more specific chestnut, using recursive iterations to replace an array, using the same algorithm, changing only when adding elements, respectively, with append and extend, you should be able to see the obvious difference from the printed results:
Using append:
deftestF1 (N): a=[] I=0 Val=N[i]delN[i] A.append (val)ifLen (n)! =0:i+ 1A.append (testF1 (n))Else:Print('End') returnAIn [164]:c= TestF1 ([3,2,5,1]) cendout[164]:[3, [2, [5, [1]]]
Using Extend:
def TestF1 (n): a = [] I = 0 val = N[i]
del
N[i] A.append (val)
if len (n)!=
0:i + 1
A.extend (t EstF1 (n))
else :
print (
"
end
"
)
return
AIn [ 166
]:c = testF1 ([3,2,5,1
166 Span style= "COLOR: #000000" >]:[ 3, 2, 5, 1]
The difference between Python extend and append