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

Antoine Pitrou solipsis at pitrou.net
Fri Oct 30 16:35:33 CET 2009


Steven D'Aprano <steve <at> pearwood.info> writes:
> 
> If you can think of any other way to efficiently cycle over the elements 
> in a set, I'm all for it :)

How about "for x in s"?

Or if you want to cycle:

>>> s = set('abc')
>>> it = itertools.cycle(s)
>>> next(it)
'a'
>>> next(it)
'c'
>>> next(it)
'b'
>>> next(it)
'a'

Or if you don't want the overhead of itertools.cycle() keeping a copy of the
set's elements:

>>> s = set('abc')
>>> it = itertools.chain.from_iterable(itertools.cycle([s]))
>>> next(it)
'a'
>>> next(it)
'c'
>>> next(it)
'b'
>>> next(it)
'a'
>>> next(it)
'c'
>>> next(it)
'b'

> I can't say I've seen one in any other languages, but Wikipedia 
> lists "pick" as a fundamental set operation:
> 
> pick(S): returns an arbitrary element of S.

Well, it's an arbitrary element. It isn't specified that it will try to return
different results in a row to satisfy the developer's aesthetical preferences...

> This page claims that Icon has an operator that returns a random element 
> of a set:
> 
> ? set( [1, 2, 3, 4, 5] )

random != arbitrary != weak-guaranteedly distinct




More information about the Python-Dev mailing list