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.


0 Comments

Leave a Reply

Avatar placeholder