Python

Using while loop to remove all specific elements from a list in Python

rdatacode provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental level, click here for more details.

Python provides function remove() to remove items in a list based on its value, but it removes only the first occurrence of instances if there are more than one such items existing in the list.

#creaate a list for car
cars = ["BMW","Mercedes","Toyota", "VOLVO","Lincoln", "Skoda","Toyota"]
#show the list
cars
#output
['BMW', 'Mercedes', 'Toyota', 'VOLVO', 'Lincoln', 'Skoda', 'Toyota']
#remove "Toyota" from list
cars.remove("Toyota")
#show car list again
cars
#output
['BMW', 'Mercedes', 'VOLVO', 'Lincoln', 'Skoda', 'Toyota']

From the code example above, we can see there is still a “Toyota” present in the list after we have used remove() function for the list. To address this issue, a while loop combined with conditional test for specific value inside the loop can be applied.

#create a list for cars
cars = ["BMW","Mercedes","Toyota", "VOLVO","Lincoln", "Skoda","Toyota"]
#show list
print(cars)
#output
['BMW', 'Mercedes', 'Toyota', 'VOLVO', 'Lincoln', 'Skoda', 'Toyota']
#using while loop, and remove "Toyota" using conditional test
while 'Toyota' in cars:
    cars.remove('Toyota')
"show list again
print(cars)
#output
['BMW', 'Mercedes', 'VOLVO', 'Lincoln', 'Skoda']

You can also watch videos on our YouTube channel for more understanding of Python programming skills.

wilsonzhang746

Recent Posts

Python Machine Learning Source Files

Click here to download Python Machine Learning Source Files !

7 days ago

Install PyTorch on Windows

PyTorch is a deep learning package for machine learning, or deep learning in particular for…

2 weeks ago

Topic Modeling using Latent Dirichlet Allocation with Python

Topic modeling is a subcategory of unsupervised machine learning method, and a clustering task in…

1 month ago

Document sentiment classification using bag-of-words in Python

For online Python training registration, click here ! Sentiment classification is a type of machine…

2 months ago

Download R Course source files

Click here to download R Course source files !

10 months ago

Download Python Course source files

Click here to download Python Course Source Files !

10 months ago