How to Append Another List to a Existing List in Python? (Differ
- 时间:2020-09-09 14:04:20
- 分类:网络文摘
- 阅读:98 次
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) —
推荐阅读:怎么给网站优化?切忌做标题党 运营笔记:SEO快排那些事儿! 运营笔记:你的网站为什么不收录?看看这篇文章的解读! 数学题:甲乙两人分别从AB两点出发 数学题:将10毫升酒装入一个圆锥形容器中 数学题:参加数学兴趣小组的同学中 数学题相遇时货车行了240km 数学题:河边放养着一群鸭子 还有10块钱哪儿去了 数学题:实验小学五(1)班、五(2)班共有89人
- 评论列表
-
- 添加评论