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

Download R Course source files

Click here to download R Course source files !

2 months ago

Download Python Course source files

Click here to download Python Course Source Files !

2 months ago

How to create a data frame from nested dictionary with Pandas in Python

For online Python training registration, click here ! Pandas provides flexible ways of generating data…

5 months ago

How to delete columns of a data frame in Python

For online Python training registration, click here ! Data frame is the tabular data object…

5 months ago

Using isin() to check membership of a data frame in Python

Click her for course registration ! When a data frame in Python is created via…

5 months ago

How to assign values to Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago