Python List Append Method Guide

In Python, the append() method of a list is used to add new elements to the end of the list. You can add elements of any data type to the list using the append() method, including numbers, strings, lists, dictionaries, and so on. Here is a simple example:

# 创建一个空列表
my_list = []

# 使用append()方法向列表中添加元素
my_list.append(1)
my_list.append('hello')
my_list.append([2, 3, 4])

print(my_list)  # 输出结果为 [1, 'hello', [2, 3, 4]]

In the example above, we first create an empty list called my_list. Then we use the append() method to sequentially add the integer 1, the string ‘hello’, and the list [2, 3, 4] to the list. The final output is [1, ‘hello’, [2, 3, 4]]. By continuously calling the append() method, we can dynamically add new elements to the list.

bannerAds