How to Append Another List to a Existing List in Python? (Differ

  • 时间:2020-09-09 14:04:20
  • 分类:网络文摘
  • 阅读:94 次

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) —

推荐阅读:
转基因食品推广需尊重消费者知情权  转基因食品试验不应是一场推销闹剧  管理总局曝光七个保健食品违法广告  预防湿疹复发可常吃清热祛湿食物  调和油乱象:市场价格和行业标准之乱  消费者该如何识别和选择食用油?  月饼是“三高”食品 六类人群不宜多吃  谁来保障转基因食品的公众知情权?  适宜老年人的秋令养阴滋补的菜肴  营养专家建议的老年人健康饮食原则 
评论列表
添加评论