Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,890 questions

51,821 answers

573 users

How to remove all the occurrences of an item from a list in Python

7 Answers

0 votes
lst = [34, 78, 34, 90, 'python', 'java', 7.28, 34]
 
for item in lst:
	if (item == 34):
		lst.remove(34)
	
print(lst)



'''
run:

[78, 90, 'python', 'java', 7.28]

'''

 



answered Jan 10, 2021 by avibootz
0 votes
lst = [34, 78, 34, 90, 'python', 'java', 7.28, 34]
 
try:
    while True:
        lst.remove(34)
except ValueError:
    pass
	
print(lst)



'''
run:

[78, 90, 'python', 'java', 7.28]

'''

 



answered Jan 10, 2021 by avibootz
0 votes
lst = [34, 78, 34, 90, 34, 'python', 'java', 7.28, 34]
  
lst = [e for e in lst if e != 34]
     
print(lst)
 
 
 
'''
run:
 
[78, 90, 'python', 'java', 7.28]
 
'''

 



answered Jan 10, 2021 by avibootz
edited Feb 18, 2023 by avibootz
0 votes
lst = [34, 78, 34, 90, 'python', 'java', 7.28, 34]
  
lst = list(filter(lambda val: val != 34, lst))
     
print(lst)
 
 
 
'''
run:
 
[78, 90, 'python', 'java', 7.28]
 
'''

 



answered Jan 10, 2021 by avibootz
edited Feb 18, 2023 by avibootz
0 votes
lst = [34, 78, 34, 90, 'python', 'java', 7.35, 34]
  
lst = list(filter((34).__ne__, lst))
  
print(lst) 



'''
run:

[78, 90, 'python', 'java', 7.35]

'''

 



answered Jan 10, 2021 by avibootz
0 votes
lst = [34, 78, 34, 90, 'python', 'java', 7.35, 34]
  
while 34 in lst: lst.remove(34)
  
print(lst) 



'''
run:

[78, 90, 'python', 'java', 7.35]

'''

 



answered Jan 10, 2021 by avibootz
0 votes
lst = [1, 2, 3, 3, 4, 5, 5, 5, 3, 3, 3.14, 7, 8]
 
for i in range(len(lst) - 1, -1, -1):  
    if lst[i] == 3:
        del lst[i]
        
print(lst) 
    
            
       
'''
run:
   
[1, 2, 4, 5, 5, 5, 3.14, 7, 8]
             
'''

 



answered Feb 18, 2023 by avibootz

Related questions

...