The difference between Python extend and append

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.