◐ Shell
clean mode source ↗

Message 377471 - Python tracker

You are right; the replacement index I called 'j' is better buried as a C index or pointer within a slice replacement. In fact, a generator expression, if one has a keep expression, or a filter call, if one has filter function, work, without the intermediate list.   Both also incorporate the keep scan index/pointer in C.  I verified that this works by defining 3 functions.

def fc(n, keep):
    mylist = list(range(n))
    mylist[:] = [x for x in mylist if keep(x)]
    return mylist

def fg(n, keep):
    mylist = list(range(n))
    mylist[:] = (x for x in mylist if keep(x))
    return mylist

def fl(n, keep):
    mylist = list(range(n))
    mylist[:] = filter(keep, mylist)
    return mylist

I added a second test expression.

    print(fc(i, keep) == fg(i, keep) == fl(i, keep) == expect)

at the 3 obvious places in the test loop above.
---

In the existing question about removing duplicates, the existing all-hashable answer
   mylist = list(set(mylist))
could be replaced by
   mylist[:] = set(mylist)