[prev in list] [next in list] [prev in thread] [next in thread] 

List:       python-ideas
Subject:    [Python-ideas] Re: Add a `count` argument to `list.remove`
From:       "Stefan Pochmann" <smpochmann () gmail ! com>
Date:       2021-12-26 21:07:17
Message-ID: 164055283794.3879.5398623387006113013 () mail ! python ! org
[Download RAW message or body]

Steven D'Aprano wrote:
> Can you sketch an O(n) algorithm for removing multiple items from an 
> array, which *doesn't* involving building a temporary new list?

Here's what I meant. Have read/write indexes, delete the gap after maxcount \
occurrences:

def remove(lst, value, maxcount):
    read = write = 0
    while maxcount > 0 and read < len(lst):
        if lst[read] == value:
            maxcount -= 1
        else:
           lst[write] = lst[read]
           write += 1
        read += 1
    del lst[write:read]

Note that the remaining elements aren't looked at, just their references are memmoved \
(or whatever del does). _______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-leave@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/DQMTVZMJ2RYG624FALIA7WGBFORMNY6T/
 Code of Conduct: http://python.org/psf/codeofconduct/


[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic