Python的列表方法append()和extend()之间的区别

Both methods append() and extend() are used to insert elements in a list.

方法append()extend()都用于在列表中插入元素。

append():

附加():

append() method appends the object at the end i.e. it appends argument as a single element at the end of the list.

append()方法将对象追加到末尾,即,将参数作为单个元素追加到列表的末尾。

Syntax:

句法:

list.append(object)

Example:

例:

list1 = [10, 20, 30]
list2 = [40, 50, 60]

# printing the list before 
# append() operation
print("list1:", list1)
print("list2:", list2)

# appending the list2 in list1
list1.append(list2)

# printing the list
print("After append, list1:", list1)

Output:

输出:

list1: [10, 20, 30]
list2: [40, 50, 60]
After append, list1: [10, 20, 30, [40, 50, 60]]

See the output, list2 is added as an object in the list1.

参见输出,将list2作为对象添加到list1中

extend():

延伸():

extend() method extends the list by appending the elements of the given object/iterable i.e. it appends argument as elements at the end of the list.

extend()方法通过添加给定对象/可迭代对象的元素来扩展列表,即,将参数作为元素添加到列表的末尾。

Syntax:

句法:

list.extend(object)

Example:

例:

list1 = [10, 20, 30]
list2 = [40, 50, 60]

# printing the list before 
# extend() operation
print("list1:", list1)
print("list2:", list2)

# appending the list2 in list1
list1.extend(list2)

# printing the list
print("After extend, list1:", list1)

Output:

输出:

list1: [10, 20, 30]
list2: [40, 50, 60]
After extend, list1: [10, 20, 30, 40, 50, 60]

See the output, list2 is added as elements in the list1.

参见输出,将list2作为元素添加到list1中

Conclusion:

结论:

Thus, the basic difference is between append() and extend() method is that append() appends the argument as an object while extend() appends the argument as elements.

因此, append()和extend()方法之间的基本区别在于append()将参数作为对象附加,而extend()将参数作为元素附加。

Read more: append() and extend() in Python

阅读更多: Python中的append()和extend()

翻译自: https://www.includehelp.com/python/difference-between-pythons-list-methods-append-and-extend.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值