深度阅读

How to add an element to a list in Python?

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

To add an element to a list in Python, you can use the append() method, which adds the element to the end of the list. Here’s an example:

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

Output:

[1, 2, 3, 4]

In this example, we define a list of numbers and then use the append() method to add the number 4 to the end of the list. The resulting list is [1, 2, 3, 4].

If you want to add multiple elements to a list, you can use the extend() method, which takes an iterable as an argument and adds each element from the iterable to the end of the list. Here’s an example:

my_list = [1, 2, 3]
other_list = [4, 5, 6]
my_list.extend(other_list)
print(my_list)

Output:

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

In this example, we define two lists and then use the extend() method to add each element from other_list to the end of my_list. The resulting list is [1, 2, 3, 4, 5, 6].

相关标签

博客作者

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