首页 > 编程知识 正文

如何在列表中追加元素

时间:2023-11-25 15:30:09 阅读:309147 作者:OICY

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

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。