Python中的append()和extend()

列出append()方法 (List append() method)

append() method is used to insert an element or a list object to the list and length of the List increased by the 1.

append()方法用于将元素或列表对象插入列表,并且列表长度增加1。

Syntax:

句法:

    List.append(element/object)

Example 1:

范例1:

# declaring a list
list1 = [10, 20, 30, 40, 50]

# printing the list before appending
print("list1: ", list1)
print("len(list1): ", len(list1))

# appending an element to the list
list1.append(60)

# printing the list after  appending
print("list1: ", list1)
print("len(list1) ", len(list1))

Output

输出量

list1:  [10, 20, 30, 40, 50]
len(list1):  5
list1:  [10, 20, 30, 40, 50, 60]
len(list1)  6

Example 2:

范例2:

# declaring a list
list1 = [10, 20, 30, 40, 50]

# printing the list before appending
print("list1: ", list1)
print("len(list1) ", len(list1))

# appending a list object to the list
list2 = [60, 70, 80]
list1.append(list2)

# printing the list after  appending
print("list1: ", list1)
print("len(list1) ", len(list1))

Output

输出量

list1:  [10, 20, 30, 40, 50]
len(list1)  5
list1:  [10, 20, 30, 40, 50, [60, 70, 80]]
len(list1)  6

列出extend()方法 (List extend() method)

extend() method is used to extend the list by inserting the given number of elements or given list and the length of the List increased by the total number of elements added.

extend()方法用于通过插入给定数量的元素或给定列表来扩展列表,并且List的长度增加所添加元素的总数。

Syntax:

句法:

    List.extend(another_list)

Note: If we append a list, then the list appended as an element to the List, thus, the length of the list increased by 1. While, if we extend a list by a list, then the list extended by the given number of elements in the list (which is passed as an argument), thus, the length of the list increased by the given number of elements in the list which is going to be added.

注意:如果我们添加一个列表,那么该列表作为元素添加到列表中,因此,列表的长度增加了1。而如果我们将列表扩展了一个列表,则该列表扩展了给定数量的列表中的元素(作为参数传递),因此,列表的长度增加了列表中要添加的元素的给定数量。

Example:

例:

# declaring a list
list1 = [10, 20, 30, 40, 50]

# printing the list before extending
print("list1: ", list1)
print("len(list1) ", len(list1))

# extending the list with another list
list2 = [60, 70, 80]
list1.extend(list2)

# printing the list after  extending
print("list1: ", list1)
print("len(list1) ", len(list1))






翻译自: https://www.includehelp.com/python/append-and-extend.aspx

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值