[Python-Dev] Retrieve an arbitrary element from a set without removing it

Steven D'Aprano steve at pearwood.info
Fri Oct 23 12:54:52 CEST 2009


On Fri, 23 Oct 2009 08:32:45 pm Willi Richert wrote:
> Hi,
>
> recently I wrote an algorithm, in which very often I had to get an
> arbitrary element from a set without removing it.
>
> Three possibilities came to mind:
...
> Of course, the third should be the fastest.

If you need one or more items chosen randomly without replacement, use a 
list:

L = list(some_set)
x = random.choice(L)

If you don't need a randomly chosen item, merely an arbitrary item, you 
can still use a list but avoid the call to random.choice:

x = list(some_set)[0]

> It nevertheless goes 
> through all the iterator creation stuff, which costs some time. I
> wondered, why the builtin set does not provide a more direct and
> efficient way for retrieving some element without removing it. Is
> there any reason for this?

I can see it being useful to iterate over the entire set, without 
removing anything. I can see it being useful to pop an arbitrary item, 
and remove it. But I can't see the use for retrieving an arbitrary 
item, leaving it in the set. What do you use this for?


> I imagine something like
>
> x = some_set.get()
>
> or
>
> x = some_set.pop(False)
>
> and am thinking about providing a patch against setobject.c
> (preferring the .get() solution being a stripped down pop()).

-1 on .pop(flag)

+0 on .get()



-- 
Steven D'Aprano


More information about the Python-Dev mailing list