[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Iterate over list and delete



On Sun, May 20, 2018 at 5:55 PM, Irv Kalb <Irv@xxxxxxxxxxxxxx> wrote:
Is there a way to do that without the list comprehension? I'm building this as part of a class, and I will not have talked about list comprehensions up until that point.

​A list comprehension is the clearest and most-pythonic way to do this (it would have been my suggestion if Daniel hadn't beat me to it).

You could modify and unroll the initial algorithm you started with to make it work. It's a lot less pretty, but it's clear algorithmically (which is the point pedagogically). It also has the advantage of being the most efficient algorithm for deletion in an array (no reallocation should be necessary, and copying is minimized).

i_read  = 0
i_write = 0
while i_read < len(myList):
    item = myList[i_read]
    i_read += 1
    if needsToBeDeleted(item):
        pass
    else:
        myList[i_write] = item
        i_write += 1
while len(myList) > i_write:
    myList.pop()


Ian​