Python logo
Sept. 2, 2019 * Python Programming

Python - Delete multiple elements from a list

Python built-in functions for lists allows any one item to be deleted in random order without disturbing any other element. To delete multiple items custom code is needed. It is very important to think through the logical sequence of events, else we can arrive at a wrong conclusion.

Remove elements at indices provided as a list

Consider removing elements from left to right. We first remove item at index 3. This means all the higher elements shift down by one. That is not what was intended. The original item at index 5 to be removed was 'f', which is now occupied by 'g'.

Removing 'g' makes the situation worse for the higher elements, which now shift down by 2. The final sequence is not what we originally intended. The right way to remove elements would be from right to left.

python remove multiple elements from list

Remove multiple items at index locations. Index locations 3, 5, 7 needs to be removed. Removing left to right results a wrong outcome.

While writing the code, let us provide the element indices to be removed in a list. However the list may not be unique and have repetitions. So we will ensure that the algorithm is robust by ignoring repeat references of items to remove.

Remove multiple characters from a list. Create unique list of indices to remove, and delete items so as not to disturb the order

txt = [*'abcdefghijk']
remove_items = [3,7,3,7,5]

# create unique sorted(descending) list of indices
unique = [*{*remove_items}]
unique.sort(reverse=True)

# delete items at positions
for position in unique:
    del txt[position]
print(txt)
Output from code:
['a', 'b', 'c', 'e', 'g', 'i', 'j', 'k']

We achieve the correct results by creating a unique list of positions, by first converting into a set. The set by definition is unique. It is then converted into a list and sorted in descending order. The elements are deleted in order from the unique list.