Question about idioms for clearing a list
Alex Martelli
aleaxit at yahoo.com
Fri Feb 10 01:32:48 EST 2006
Bryan Olson <fakeaddress at nowhere.org> wrote:
...
> > I agree that emptying is logically the same thing for all of these
> > types. Beyond that, they don't seem to have a lot in common. It's
...
> > Do you really have a usecase for this? It seems to me that your
> > argument is pretty hollow.
>
> Sure:
>
> if item_triggering_end in collection:
> handle_end(whatever)
> collection.clear()
>
> Or maybe moving everything from several collections into
> a single union:
>
> big_union = set()
> for collection in some_iter:
> big_union.update(t)
> collection.clear()
I was thinking of something different again, from a use case I did have:
def buncher(sourceit, sentinel, container, adder, clearer):
for item in sourceit:
if item == sentinel:
yield container
clearer()
else
adder(item)
yield container
s = set()
for setbunch in buncher(src, '', s, s.add, s.clear): ...
d = dict()
for dictbunch in buncher(src, '', d, lambda x: d.setdefault(x,''),
d.clear): ...
L = list()
for listbunch in buncher(src, '', L, L.append,
lambda: L.__setslice__(0,len(L),[])): ...
the dict case is semi-goofy (since some arbitrary value must be set, one
ends up with a lambda willy nilly), but the list case is even worse,
with that horrid "lambda calling __setslice__" (eek).
BTW, we do have other mutable collections...:
import collections
q = collections.deque()
for qbunch in buncher(src, q, q.append, q.clear): ...
just as neat as a set.
So what is the rationale for having list SO much harder to use in such a
way, than either set or collections.deque? (For dict, I can see the
rationale for not having an 'addkey', even though the presence of class
method 'fromkeys' weakens that rationale... but for list, I cannot see
any reason that makes sense to me).
Alex
More information about the Python-list
mailing list