x = [20]# List passed to the append(object) method is treated as a single object.x.append([21, 22, 23])# Hence the resultant list length will be 2print(x)--> [20, [21, 22, 23]]
extend(list)本质上连接了两个列表。
x = [20]# The parameter passed to extend(list) method is treated as a list.# Eventually it is two lists being concatenated.x.extend([21, 22, 23])# Here the resultant list's length is 4print(x)--> [20, 21, 22, 23]
>>> 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.
/* 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_one(a_list, element):a_list.append(element)
def extend_one(a_list, element):"""creating a new list is semantically the most directway to create an iterable to give to extend"""a_list.extend([element])
import timeit
lis = [1, 2, 3]
# 'extend' is equivalent to thislis = lis + list(iterable)
# 'append' simply appends its argument as the last element to the list# as long as the argument is a valid Python objectlist.append(object)
def append_o(a_list, element):a_list.append(element)print('append:', end = ' ')for item in a_list:print(item, end = ',')print()
def extend_o(a_list, element):a_list.extend(element)print('extend:', end = ' ')for item in a_list:print(item, end = ',')print()append_o(['ab'],'cd')
extend_o(['ab'],'cd')append_o(['ab'],['cd', 'ef'])extend_o(['ab'],['cd', 'ef'])append_o(['ab'],['cd'])extend_o(['ab'],['cd'])