Remove items from a list while iterating without using extra memory in Python

后端 未结 8 948
生来不讨喜
生来不讨喜 2020-12-10 05:45

My problem is simple: I have a long list of elements that I want to iterate through and check every element against a condition. Depending on the outcome of the condition I

8条回答
  •  情书的邮戳
    2020-12-10 06:13

    Here is an alternative answer for if you absolutely have to remove the items from the original list, and you do not have enough memory to make a copy - move the items down the list yourself:

    def walk_list(list_of_g):
        to_idx = 0
        for g_current in list_of_g:
            if not subtle_condition(g_current):
                list_of_g[to_idx] = g_current
                to_idx += 1
        del list_of_g[to_idx:]
    

    This will move each item (actually a pointer to each item) exactly once, so will be O(N). The del statement at the end of the function will remove any unwanted items at the end of the list, and I think Python is intelligent enough to resize the list without allocating memory for a new copy of the list.

提交回复
热议问题