Search code examples
pythonpython-3.xlist-manipulation

Need to remove some element positions in a list of lists, is there a more efficient way to this without making new output list?


I have a list called "candidate_keywords_all" containing three inner lists of strings. The other list of lists called "positions_to_remove_all" has index positions of words to be removed. My code below does this by making a new output list. Is there a way without using a new list? If I modify original list using pop method, each pop affects the index positions of remaining elements and they no longer match up and cause index errors. Note that the inner list for positions can be empty too.

candidate_keywords_all =[
    ['list1_word1', 'list1_word2', 'list1_word3'],
    ['list2_word1', 'list2_word2', 'list2_word3', 'list2_word4', 'list2_word5', 'list2_word6'],
    ['list3_word1', 'list3_word2']
]

positions_to_remove_all =[ [0, 2], [1, 3, 5], [] ]

## extract the Selected keywords into new data structure
final_keywords = []
for each_index_positions, each_candidate_keywords in \
    zip(positions_to_remove_all, candidate_keywords_all):
    temp_arr = [keyword for idx, keyword in enumerate(each_candidate_keywords) if idx not in each_index_positions]
    final_keywords.append(temp_arr)

for each_candidate_keywords, each_index_positions, each_final_keywords in zip(candidate_keywords_all, positions_to_remove_all, final_keywords):
    print(f"BEFORE = {each_candidate_keywords}\nRemove positions = {each_index_positions}\nAFTER = {each_final_keywords}\n\n")

Any inputs appreciated, thank you.


Solution

  • You can use del to remove an element by index directly from a list, in-place.
    Note I iterate the positions in reverse order because otherwise after removal the remaining indexes all change places.

    for each_index_positions, each_candidate_keywords in zip(
        positions_to_remove_all, candidate_keywords_all
    ):
        for pos in reversed(each_index_positions):
            del each_candidate_keywords[pos]