Quelle est la différence entre les méthodes de liste Python paramètre#39;s appendent et prolongent

Mots clés : pythonlistdata-structuresappendextendpython

meilleur 5 Réponses Quelle est la différence entre les méthodes de liste Python paramètre#39;s appendent et prolongent

vote vote

90

x = [1, 2, 3] x.append([4, 5]) print(x) 
x = [1, 2, 3] x.extend([4, 5]) print(x) 
vote vote

82

>>> li = ['a', 'b', 'mpilgrim', 'z', 'example'] >>> li ['a', 'b', 'mpilgrim', 'z', 'example']  >>> li.append("new") >>> li ['a', 'b', 'mpilgrim', 'z', 'example', 'new']  >>> li.append(["new", 2]) >>> li ['a', 'b', 'mpilgrim', 'z', 'example', 'new', ['new', 2]]  >>> li.insert(2, "new") >>> li ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', ['new', 2]]  >>> li.extend(["two", "elements"]) >>> li ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', ['new', 2], 'two', 'elements'] 
vote vote

76

my_list.append(object)  
>>> my_list ['foo', 'bar'] >>> my_list.append('baz') >>> my_list ['foo', 'bar', 'baz'] 
>>> another_list = [1, 2, 3] >>> my_list.append(another_list) >>> my_list ['foo', 'bar', 'baz', [1, 2, 3]]                      #^^^^^^^^^--- single item at the end of the list. 
my_list.extend(iterable) 
>>> my_list ['foo', 'bar'] >>> another_list = [1, 2, 3] >>> my_list.extend(another_list) >>> my_list ['foo', 'bar', 1, 2, 3] 
>>> my_list.extend('baz') >>> my_list ['foo', 'bar', 1, 2, 3, 'b', 'a', 'z'] 
    /* This over-allocates proportional to the list size, making room      * for additional growth.  The over-allocation is mild, but is      * enough to give linear-time amortized behavior over a long      * sequence of appends() in the presence of a poorly-performing      * system realloc(). 
def append(alist, iterable):     for item in iterable:         alist.append(item)          def extend(alist, iterable):     alist.extend(iterable) 
import timeit  >>> min(timeit.repeat(lambda: append([], "abcdefghijklmnopqrstuvwxyz"))) 2.867846965789795 >>> min(timeit.repeat(lambda: extend([], "abcdefghijklmnopqrstuvwxyz"))) 0.8060121536254883 
def append_one(a_list, element):     a_list.append(element)  def extend_one(a_list, element):     """creating a new list is semantically the most direct     way to create an iterable to give to extend"""     a_list.extend([element])  import timeit 
>>> min(timeit.repeat(lambda: append_one([], 0))) 0.2082819009956438 >>> min(timeit.repeat(lambda: extend_one([], 0))) 0.2397019260097295 
vote vote

66

>>> a = [1, 2, 3] >>> a.append([4, 5, 6]) >>> a [1, 2, 3, [4, 5, 6]] 
vote vote

54

>>> a = [1,2] >>> a.append(3) >>> a [1,2,3] 
>>> a.append([4,5]) >>> a >>> [1,2,3,[4,5]] 
>>> a = [1,2] >>> a.extend([3]) >>> a [1,2,3] 
>>> a.extend([4,5,6]) >>> a [1,2,3,4,5,6] 
>>> x = [1,2] >>> x.append(3) >>> x [1,2,3] 
>>> x = [1,2] >>> x.extend([3]) >>> x [1,2,3] 
>>> x = [1,2] >>> x.append([3,4]) >>> x [1,2,[3,4]] 
>>> z = [1,2]  >>> z.extend([3,4]) >>> z [1,2,3,4] 

Questions similaires