深度阅读

How to add an element to a list in Python

作者
作者
2023年08月22日
更新时间
9.01 分钟
阅读时间
0
阅读量

To add an element to a list in Python, you can use the append() method or the insert() method.

Here’s an example using the append() method:

my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]

In this example, the append() method is used to add the number 4 to the end of the my_list list.

Here’s an example using the insert() method:

my_list = [1, 2, 3]
my_list.insert(1, 4)
print(my_list) # Output: [1, 4, 2, 3]

In this example, the insert() method is used to add the number 4 to index 1 of the my_list list, pushing the original element at that position and subsequent elements one index to the right.

You can also use the extend() method to append multiple elements from another list to the end of the current list.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。