ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python List 中的append 和 extend 的区别

2022-07-17 15:00:19  阅读:208  来源: 互联网

标签:extend Python List list list1 world hello append


方法的参数不同

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']

标签:extend,Python,List,list,list1,world,hello,append
来源: https://www.cnblogs.com/jack-nie-23/p/16486862.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有