Python List 中的append 和 extend 的区别

方法的参数不同

append 方法是向原list的末尾添加一个对象(任意对象;如元组,字典,列表等),且只占据一个原list的索引位,添加后无返回值,直接在原列表中添加。 list.append(object)

list1 = ["hello", "world"]
list2 = "hello"
list_s = ["Python"]
list_s.append(list1)
list_s.append(list2)
print(list_s)
>> ['Python', ['hello', 'world']]
>> ['Python', ['hello', 'world'], 'hello']

extend 方法是向原list的末尾中添加一个可迭代的序列,序列中有多少个对象就会占据原list多少个索引位置,添加后无返回值,直接在原列表中添加。 list.extend(sequence)

list1 = ["hello", "world"]
list2 = "hello"
list_s = ["Python"]
list_s.extend(list1)
list_s.extend(list2)			# 添加字符串时,字符串为可迭代序列,且序列元素为字符串中的字符
print(list_s)
>> ['Python', 'hello', 'world']
>> ['Python', 'hello', 'world', 'h', 'e', 'l', 'l', 'o']

对添加对象的处理方式不同

append 在内存中,是直接添加的追加对象的地址,没有创建新的存储空间,即修改原始的追加值,被追加的list也会被相应改变

list1 = ["hello", "world"]
list_s = ["Python"]
list_s.append(list1)
print(list_s)
list1[0] = "C"		# 原始追加值改变,list_s 也相应改变
print(list_s)

>> ['Python', ['hello', 'world']]
>> ['Python', ['C', 'world']]

extend 在内存中,是直接复制的追加对象的值,创建了新的存储空间,原始追加值和添加后的值互不干扰

list1 = ["hello", "world"]
list_s = ["Python"]
list_s.extend(list1)
print(list_s)
list1[0] = "C"		# 原始追加值改变,list_s 不被影响,因为其创建了新的存储空间
print(list_s)

>> ['Python', 'hello', 'world']
>> ['Python', 'hello', 'world']
posted @ 2022-07-17 14:55  jacknie23  阅读(296)  评论(0编辑  收藏  举报