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.
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.
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.
# Python - Delete multiple elements from a list
# SEO Google page rank and web traffic
# Python: Random access generator for multi value sublist yield
# Python: Enumerate counter for loops over list, tuple, string
# Pandas - Read, skip and customize column headers for read_csv
# Pandas - Selecting data rows and columns using read_csv
# Pandas - Space, tab and custom data separators
# Sample data for Python tutorials
# Pandas - Purge duplicate rows
# Pandas - Concatenate or vertically merge dataframes
# Pandas - Search and replace values in columns
# Pandas - Count rows and columns in dataframe
# Pandas - Adding new static columns
# Python - Hardware and operating system information
# Pandas - Remove or drop columns from Pandas dataframe