当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python list remove()用法及代码示例


remove()是Python编程语言中的内置函数,可从列表中删除给定的对象。它不返回任何值。

用法:

list_name.remove(obj) 

参数:


obj - object to be removed from the list 

返回值:

 The method does not return any value 
but removes the given object from the list.

注意:它从列表中删除该对象的第一个匹配项。
代码#1:

# Python3 program to demonstrate the use of  
# remove() method  
  
  
# the first occurrence of 1 is removed from the list  
list1 = [ 1, 2, 1, 1, 4, 5 ]  
list1.remove(1)  
print(list1)  
  
# removes 'a' from list2  
list2 = [ 'a', 'b', 'c', 'd' ]  
list2.remove('a')  
print(list2)

输出:

[2, 1, 1, 4, 5]
['b', 'c', 'd']

错误:

It returns ValueError when the passed object 
is not present in the list

代码#2:

# Python3 program for the error in  
# remove() method  
  
  
# removes 'e' from list2  
list2 = [ 'a', 'b', 'c', 'd' ]  
list2.remove('e')  
print(list2)

输出:

Traceback (most recent call last):
  File "/home/e35b642d8d5c06d24e9b31c7e7b9a7fa.py", line 8, in 
    list2.remove('e') 
ValueError:list.remove(x):x not in list

实际应用:
给定一个列表,从列表中删除所有1,然后打印列表。

代码#3:

# Python3 program for practical application 
# of removing 1 untill all 1 are removed from the list  
   
   
list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5] 
  
# looping till all 1's are removed 
while (list1.count(1)):
    list1.remove(1)  
      
print(list1) 

输出:

[2, 3, 4, 4, 5]



注:本文由纯净天空筛选整理自Striver大神的英文原创作品 Python list remove()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。