How to Append Another List to a Existing List in Python? (Differ
- 时间:2020-09-09 14:04:20
- 分类:网络文摘
- 阅读:143 次
Let’s you have a list in Python:
1 | a = [1, 2, 3, 4] |
a = [1, 2, 3, 4]
And you have another list in Python:
1 | b = [5, 6, 7, 8] |
b = [5, 6, 7, 8]
You can concatenate two lists by simply using + operator, which will leave both lists untouched and return a copy of the concatenated list.
1 | a + b # [1, 2, 3, 4, 5, 6, 7, 8] |
a + b # [1, 2, 3, 4, 5, 6, 7, 8]
You can use extend() method of the array, which allows us to append all the elements from another list to it. This will modify the original list.
1 2 3 | # c is None c = a.extend(b) # a is now [1, 2, 3, 4, 5, 6, 7, 8] |
# c is None c = a.extend(b) # a is now [1, 2, 3, 4, 5, 6, 7, 8]
The append() on the other hand, appends an element to the list. For example,
1 2 3 | a = [1, 2, 3, 4] a.append(5) # a is now [1, 2, 3, 4, 5] |
a = [1, 2, 3, 4] a.append(5) # a is now [1, 2, 3, 4, 5]
The append returns None. You can use append to achieve what the extend does.
1 2 3 | def extend(a, b): for x in b: a.append(x) |
def extend(a, b):
for x in b:
a.append(x)–EOF (The Ultimate Computing & Technology Blog) —
推荐阅读:公众最担心食品添加有毒有害物质 食品安全蓝皮书发布 解读2012食品问题 购买保健食品要认准“蓝帽子”标志 食品安全问题公众和媒体也有话语权 初春食补:胡椒根对症食疗祛除寒湿 纯天然食品与绿色食品有何区别 铝瓜子事件提醒食品安全检测应扩容 香港限奶令实施掀新一轮水货攻防战 健康饮食四字诀:一鲜二咸三厚四甜 电脑族健康饮食要注意八个方面
- 评论列表
-
- 添加评论