Answers for "remove item from list if it exists python"

0

remove item from list if it exists python

# 1) Almost-English style:
if thing in some_list:
	some_list.remove(thing)
    
# 2) Duck type, EAFP style:
with suppress(ValueError, AttributeError):
    some_list.remove(thing)
    
# 3) Filter it out
some_list = filter(lambda x: x != thing, some_list)

# 4) List comprehension 
some_list = [ x for x in some_list if x != thing ]
Posted by: Guest on January-26-2022

Code answers related to "remove item from list if it exists python"

Python Answers by Framework

Browse Popular Code Answers by Language