Python之 list 用法三

向list中插入一个元素:list.insert(i,x)

list.insert(i,x)也是对list元素的增加。只不过是可以在任何位置增加一个元素。

>>> all_users
['qiwsir', 'github', 'io']
>>> all_users.insert("python")      #list.insert(i,x),要求有两个参数,少了就报错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: insert() takes exactly 2 arguments (1 given)

>>> all_users.insert(0,"python")
>>> all_users
['python', 'qiwsir', 'github', 'io']

>>> all_users.insert(1,"http://")
>>> all_users
['python', 'http://', 'qiwsir', 'github', 'io']

>>> length = len(all_users)
>>> length
5

>>> all_users.insert(length,"algorithm")
>>> all_users
['python', 'http://', 'qiwsir', 'github', 'io', 'algorithm']

小结:

  • list.insert(i,x),将新的元素x 插入到原list中的list[i]前面

  • 如果i==len(list),意思是在后面追加,就等同于list.append(x)

删除list中的元素:

list.remove(x)和list.pop([i])

例1:

>>> all_users
['python', 'qiwsir', 'github', 'io', 'algorithm']
>>> "python" in all_users       #这里用in来判断一个元素是否在list中,在则返回True,否则返回False
True

>>> if "python" in all_users:
...     all_users.remove("python")
...     print all_users
... else:
...     print "'python' is not in all_users"
...
['qiwsir', 'github', 'io', 'algorithm']     #删除了"python"元素

>>> if "python" in all_users:
...     all_users.remove("python")
...     print all_users
... else:
...     print "'python' is not in all_users"
...
'python' is not in all_users        #因为已经删除了,所以就没有了。

例2:

>>> all_users
['qiwsir', 'github', 'io', 'algorithm']
>>> all_users.pop()     #list.pop([i]),圆括号里面是[i],表示这个序号是可选的
'algorithm'             #如果不写,就如同这个操作,默认删除最后一个,并且将该结果返回

>>> all_users
['qiwsir', 'github', 'io']

>>> all_users.pop(1)        #指定删除编号为1的元素"github"
'github'

>>> all_users
['qiwsir', 'io']
>>> all_users.pop()
'io'

>>> all_users           #只有一个元素了,该元素编号是0
['qiwsir']
>>> all_users.pop(1)    #但是非要删除编号为1的元素,结果报错。注意看报错信息
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: pop index out of range      #删除索引超出范围,就是1不在list的编号范围之内

转载于:https://my.oschina.net/yangy8/blog/668966

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值