• python中的del,remove,pop有什么区别


    python中有3个删除元素的方法:del remove pop

    虽然它们都是删除元素,用于删除列表、字符串等里面的元素,但是用法可不完全一样,元组由于是不可变的,所以不能使用哦!那么接下来就来看看它们之间有什么区别:

    # 代码源列表如下:
    a_list = ['Mecell', 18, 'Python', True, None, [1, 2, 3], 'Python']

    1. del——指定索引值删除

    # del 列表[索引值]
    del a_list[1]
       
    # 源列表:
    ['Mecell', 18, 'Python', True, None, [1, 2, 3], 'Python']
    
    # del删除数据后的列表:
    ['Mecell', 'Python', True, None, [1, 2, 3], 'Python']  
    

    2. remove——默认移除第一个出现的元素

    # 列表.remove[删除对象] 
    # 对象可以是列表里面的任何数据类型:字符串、数字、bool等
    a_list.remove['Python']
    
    # 源列表:
    ['Mecell', 18, 'Python', True, None, [1, 2, 3], 'Python']
    # remove删除数据后的列表:
    ['Mecell', 18, True, None, [1, 2, 3], 'Python']
    
    从结果可以看出,列表里面有两个'Python',但是实际上只是删除了第一个,最后一个并没有删除,这就是remove的特点,需要大家注意!    
    

      

    3. pop——括号内不添加索引值,则默认删除列表中的最后一个元素;反之则默认根据索引值删除 

    # 列表.pop() --删除最后一个元素
    a_list.pop()
    
    # 源列表:
    ['Mecell', 18, 'Python', True, None, [1, 2, 3], 'Python']
    # pop删除数据后的列表:
    ['Mecell', 18, 'Python', True, None, [1, 2, 3]]
    
    
    # 列表.pop(索引值) --指定索引值删除
    a_list.pop(3) 
    # 源列表: ['Mecell', 18, 'Python', True, None, [1, 2, 3], 'Python'] # pop删除数据后的列表: ['Mecell', 18, 'Python', None, [1, 2, 3], 'Python']

      

    以上就是del,remove和pop的用法区别啦!

  • 相关阅读:
    Scrum Meeting 11.11
    Scrum Meeting 11.10
    Scrum Meeting 11.09
    Scrum Meeting 11.08
    Scrum Meeting 11.07
    Scrum Meeting 11.06
    Scrum Meeting 11.05
    Scrum Meeting 11.04
    团队博客-应用功能说明书
    Scrum Meeting 11.03
  • 原文地址:https://www.cnblogs.com/mecell224/p/11116839.html
Copyright © 2020-2023  润新知