python 添加进列表
Python中使用列表可以方便地存储和操作一些数据,而添加元素进列表是一项基本操作。
在Python中,可使用append()方法向列表中添加元素:
my_list = ['apple', 'banana', 'orange'] my_list.append('pear') print(my_list)
运行上述代码会输出:
['apple', 'banana', 'orange', 'pear']
可以看到,‘pear’被成功添加到了my_list中。
除append()方法,还有一些其他方法可以向列表中添加元素。
例如,可使用insert()方法在指定位置插入元素:
my_list = ['apple', 'banana', 'orange'] my_list.insert(1, 'pear') print(my_list)
运行上述代码会输出:
['apple', 'pear', 'banana', 'orange']
可以看到,‘pear’被成功插入到了my_list的第二个位置。
除方法,也能够使用加号(+)将两个列表合并成一个新的列表:
list1 = ['apple', 'banana'] list2 = ['orange', 'pear'] my_list = list1 + list2 print(my_list)
运行上述代码会输出:
['apple', 'banana', 'orange', 'pear']
my_list中包括了list1和list2的元素。
文章来源:丸子建站
文章标题:python 添加进列表
https://www.wanzijz.com/view/82415.html