欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python新手学习基础之数据结构-列表2 添加 博客分类: Python 列表appendinsert 

程序员文章站 2024-03-19 10:51:10
...

insert

 

除了使用索引,我们还可以用列表的insert方法,在列表的指定位置添加新的值。

insert的用法:

 

list.insert(index, item)

例如:

 

 

like_animals = ['dog', 'elephant', 'rabbit', 'lion']
#使用列表的insert方法为like_animals添加元素
like_animals.insert(3,'pig')
print(like_animals)

 
Python新手学习基础之数据结构-列表2 添加
            
    
    博客分类: Python 列表appendinsert 
 

 

当这个索引超出列表的最大范围时,会在最后插入,或者在最前面插入(当使用负数索引时)。

 

 

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新手学习基础之数据结构-列表2 添加
            
    
    博客分类: Python 列表appendinsert 
 

 

 

  • Python新手学习基础之数据结构-列表2 添加
            
    
    博客分类: Python 列表appendinsert 
  • 大小: 5.1 KB
  • Python新手学习基础之数据结构-列表2 添加
            
    
    博客分类: Python 列表appendinsert 
  • 大小: 5.2 KB