如何向列表中添加元素

2024 年 8 月 29 日 | 阅读 2 分钟

Python提供了内置方法来追加或添加元素到列表中。我们也可以将一个列表追加到另一个列表中。这些方法如下。

  • append(elmt) - 它将值追加到列表的末尾。
  • insert(index, elmt) - 它在指定的索引位置插入值。
  • extends(iterable) - 它通过添加可迭代对象来扩展列表。

让我们通过以下示例来理解这些方法。

1. append(elmt)

此函数用于在列表末尾添加元素。示例如下。

示例 -

输出

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

2. insert(index, elmt)

insert()函数在给定的索引位置添加元素。当我们需要在特定位置插入元素时,它很有用。示例如下。

示例 -

输出

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. extend(iterable)

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

示例 -

输出

[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']