python中nums.append_Python程序中的append()和extend()

在本教程中,我们将学习列表的最常用方法,即append()和extend()。让我们一一看。

附加()

append()方法用于在list的末尾插入元素。append()方法的时间复杂度为O(1)。

语法list.append(element) -> element can be any data type from the list of data types.

让我们看一些例子。

示例# initializing a list

nums = [1, 2, 3, 4]

# displaying the list

print('----------------Before Appending-------------------')

print(nums)

print()

# appending an element to the nums

# 5 will be added at the end of the nums

nums.append(5)

# displaying the list

print('----------------After Appending-------------------')

print(nums)

输出结果

如果运行上面的程序,您将得到以下结果。----------------Before Appending-------------------

[1, 2, 3, 4]

----------------After Appending-------------------

[1, 2, 3, 4, 5]

附加列表。

示例# initializing a list

nums = [1, 2, 3, 4]

# displaying the list

print('----------------Before Appending-------------------')

print(nums)

print()

# appending an element to the nums

# 5 will be added at the end of the nums

nums.append([1, 2, 3, 4])

# displaying the list

print('----------------After Appending-------------------')

print(nums)

输出结果

如果运行上面的程序,您将得到以下结果。----------------Before Appending-------------------

[1, 2, 3, 4]

----------------After Appending-------------------

[1, 2, 3, 4, [1, 2, 3, 4]]

延伸()

extend()方法用于延长具有可迭代项的列表。extend()方法的时间复杂度为O(n),其中n是可迭代的长度。

语法list.extend(iterable) -> extend method iterates over the iterable and appends all the elements to the list.

让我们看一些例子。

示例# initializing a list

nums = [1, 2, 3, 4]

# displaying the list

print('----------------Before Appending-------------------')

print(nums)

print()

# extending the list nums

# 5, 6, 7 will be added at the end of the nums

nums.extend([5, 6, 7])

# displaying the list

print('----------------After Appending-------------------')

print(nums)

输出结果

如果运行上面的程序,您将得到以下结果。----------------Before Appending-------------------

[1, 2, 3, 4]

----------------After Appending-------------------

[1, 2, 3, 4, 5, 6, 7]

如果将字符串传递给extend()方法怎么办?让我们来看看。

示例# initializing a list

nums = ['h', 'i']

# displaying the list

print('----------------Before Appending-------------------')

print(nums)

print()

# extending the list nums

# 5, 6, 7 will be added at the end of the nums

nums.extend('hello')

# displaying the list

print('----------------After Appending-------------------')

print(nums)

输出结果

如果运行上面的程序,您将得到以下结果。----------------Before Appending-------------------

['h', 'i']

----------------After Appending-------------------

['h', 'i', 'h', 'e', 'l', 'l', 'o']

结论

希望您喜欢本教程。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值