Removing Multiple Values inside List [Python]
Do you have any experience with manipulating list of python when you need to remove one or multiple values inside of it, imagine we have a list like this:
fruits = [’banana’, ‘orange’, ‘watermelon’, ‘apple’]
Then you need to remove value based on it's index like “banana” and “apple” inside “fruits” list, how to make them work ? looping over the list values and delete them by an index number ?
Here what can we get, about delete those by loop
fruits = [’banana’, ‘orange’, ‘watermelon’, ‘apple’] index_to_delete = [0, 3] for idx, fruit in enumerate(fruits): if idx in index_to_delete: del fruits[idx] # This just works on first deletion
As you can see above, you code will breaks after you do delete on second time on loop, because the index you’re going to remove is changed as time as the loop process running. So what can we do about those ?
Because the index of those list will be change every time we remove the value, we can do this by populate a new list values without deleted values inside of it.
fruits = [’banana’, ‘orange’, ‘watermelon’, ‘apple’] index_to_delete = [0, 3] fruits = [fruit for idx, fruit in enumerate(fruits) if idx not in index_to_delete] # Here what you will get fruits = [’orange’, ‘watermelon’]
Simple method above shows you how you populate a new list values without including the deleted values inside them.









