In this post we will be creating a script in Python that will remove all instances of an item from within. Lists in Pyhon provide a means of storing multiple items into a single variable.
We start by creating a list which can be seen below.
MyList = ['Stevie', 'Will', 'Dustin', 'Will', 'Jim', 'Will', 'Mike']
In this example we will be removing all instances of ‘Will’ within our list, to do this we be making use of the remove() method which by default only removes one instance. To remove all we will be place the remove method in a while loop.
The source code for this project can be found below.
MyList = ['Stevie', 'Will', 'Dustin', 'Will', 'Jim', 'Will', 'Mike'] try: while True: MyList.remove('Will') except ValueError: pass print(MyList)