全国旗舰校区

不同学习城市 同样授课品质

北京

深圳

上海

广州

郑州

大连

武汉

成都

西安

杭州

青岛

重庆

长沙

哈尔滨

南京

太原

沈阳

合肥

贵阳

济南

下一个校区
就在你家门口
+
当前位置:首页  >  技术干货

如何在列表中追加元素

发布时间:2023-07-21 17:00:38
发布人:xqq

Python 提供了向列表追加或添加元素的内置方法。我们也可以将一个列表附加到另一个列表中。下面给出了这些方法。

    追加(elmt) - 它在列表末尾追加值。

    插入(index,elmt) - 它在指定的索引位置插入值。

    扩展(可迭代)- 通过添加可迭代对象扩展列表。

让我们通过下面的例子来理解这些方法。

1.附录(ELT)

该函数用于在列表末尾添加元素。下面给出了例子。

示例-


names = ["Joseph", "Peter", "Cook", "Tim"]

print('Current names List is:', names)

new_name = input("Please enter a name:\n")
names.append(new_name)  # Using the append() function

print('Updated name List is:', names)

输出:

Current names List is: ['Joseph', 'Peter', 'Cook', 'Tim']
Please enter a name:
Devansh
Updated name List is: ['Joseph', 'Peter', 'Cook', 'Tim', 'Devansh']

2.插入(索引,elmt)

函数的作用是:在给定的索引位置添加元素。当我们想要在特定位置插入元素时,这是有益的。下面给出了例子。

示例-


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

print('Current Numbers List: ', list1)

el = list1.insert(3, 77)
print("The new list is: ",list1)

n = int(input("enter a number to add to list:\n"))

index = int(input('enter the index to add the number:\n'))

list1.insert(index, n)

print('Updated Numbers List:', list1)

输出:

Current Numbers List:  [10, 20, 30, 40, 50]
The new list is:  [10, 20, 30, 77, 40, 50]
enter a number to add to list:
 45
enter the index to add the number:
1
Updated Numbers List: [10, 45, 20, 30, 77, 40, 50]

3.扩展(可迭代)

extends()函数用于将可迭代元素添加到列表中。它接受可迭代对象作为参数。下面是添加可迭代元素的示例。

示例-


list1 = [10,20,30]
list1.extend(["52.10", "43.12" ])  # extending list elements
print(list1)
list1.extend((40, 30))  # extending tuple elements
print(list1)
list1.extend("Apple")  # extending string elements
print(list1)

输出:

[10, 20, 30, '52.10', '43.12']
[10, 20, 30, '52.10', '43.12', 40, 30]
[10, 20, 30, '52.10', '43.12', 40, 30, 'A', 'p', 'p', 'l', 'e']
#python教程

相关文章

为什么Hadoop是用Java实现的?

为什么Hadoop是用Java实现的?

2023-10-15
Java8引入Lambda表达式的利弊是什么?

Java8引入Lambda表达式的利弊是什么?

2023-10-15
同步请求和异步请求的区别是什么?

同步请求和异步请求的区别是什么?

2023-10-15
云平台是什么?

云平台是什么?

2023-10-15

最新文章

常见网络安全面试题:Windows常用的命令有哪些?

常见网络安全面试题:Windows常用的命令有哪些?

2023-10-09
常见网络安全面试题:根据设备告警如何展开排查?

常见网络安全面试题:根据设备告警如何展开排查?

2023-10-09
常见网络安全面试题:mysql加固呢?(数据库加固)

常见网络安全面试题:mysql加固呢?(数据库加固)

2023-10-09
常见网络安全面试题:windows和linux加固?(操作系统加固)

常见网络安全面试题:windows和linux加固?(操作系统加固)

2023-10-09
在线咨询 免费试学 教程领取