Skip to content

Python code snippet – How to remove elements from a list?

# Basic syntax:

# Note, .remove(element) removes the first matching element it finds in
# 	the list.

# Example usage:
animals = ['cat', 'dog', 'rabbit', 'guinea pig', 'rabbit']
--> ['cat', 'dog', 'guinea pig', 'rabbit'] # Note only 1st instance of
#	rabbit was removed from the list. 

# Note, if you want to remove all instances of an element, convert the
#	list to a set and back to a list, and then run .remove(element)	E.g.:
animals = list(set['cat', 'dog', 'rabbit', 'guinea pig', 'rabbit']))
--> ['cat', 'dog', 'guinea pig']
See also  How to modulus in Python?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.