insert
除了使用索引,我们还可以用列表的insert方法,在列表的指定位置添加新的值。
insert的用法:
list.insert(index, item)
例如:
like_animals = ['dog', 'elephant', 'rabbit', 'lion']
#使用列表的insert方法为like_animals添加元素
like_animals.insert(3,'pig')
print(like_animals)

当这个索引超出列表的最大范围时,会在最后插入,或者在最前面插入(当使用负数索引时)。
append
使用append()可以在列表尾端添加新的值,但一次只能添加一个值。
append的用法:
list.append(item)
例如:
like_animals = ['dog', 'elephant', 'rabbit', 'lion']
#给like_animals尾端添加一个新的元素
like_animals.append('kongfu')
print(like_animals)
更多学习内容,就在码芽网http://www.mayacoder.com/lesson/index

本文介绍了Python中列表的两种常用添加方法:insert和append。insert方法允许在列表的任意位置插入元素,而append则是在列表末尾添加。通过示例展示了如何使用这两种方法来高效管理列表数据。
2123

被折叠的 条评论
为什么被折叠?



