[Python-Dev] Retrieve an arbitrary element from a set withoutremoving it
Guido van Rossum
guido at python.org
Tue Nov 3 19:56:44 CET 2009
On Tue, Nov 3, 2009 at 12:20 AM, Yuvgoog Greenle <ubershmekel at gmail.com> wrote:
> On Tue, Nov 3, 2009 at 12:19 AM, Greg Ewing <greg.ewing at canterbury.ac.nz>
> wrote:
>>
>> Cameron Simpson wrote:
>>
>>> Personally, I'm for the iteration spec in a lot of ways.
>>>
>>> Firstly, a .get()/.pick() that always returns the same element feels
>>> horrible. Is there anyone here who _likes_ it?
>>
>
> State might cause people to use this to iterate which would be just plain
> wrong. The 2 things I have a bad feeling about is:
> 1. random.choice could be a pythonic alternative to what some have mentioned
> here but it doesn't work on sets. The following code raises TypeError: 'set'
> object does not support indexing:
> import random
> random.choice(set([1,2,3,4,5,6]))
There is a huge difference between picking a random element of a set
and picking an arbitrary one. Algorithms that need randomness *must*
use the random generator (and because the hash table implementation
doesn't provide O(1) access they will have to use a list first).
Algorithms that don't need randomness should not be forced to pay for
the (considerable!) cost of calling the random number generator, and
must accept that the element selected may be predictable.
> this is kinda ironic: http://en.wikipedia.org/wiki/Axiom_of_choice
Also irrelevant. That Axiom is only interesting for infinite sets,
which Python does not support (at least not using the set builtin --
you can of course write your own symbolic algebra package in Python
that can be used to represent certain infinite sets, though you still
won't be able to iterate over all of their elements :-).
> 2. If I store objects in a set and modify their attributes I have no O(1)
> way of getting the objects back if I stumble upon an equivalent object. In
> cases like that I'd have to either iterate over the set or use a dict with
> key == value. I have a feeling the "get" or "peek" api could cater to this
> need. A use case for this could be an implementation of a cookie jar with a
> set of cookies where equivalence is defined by the name and domain.
Sets are what they are. If they don't fit your requirements, don't use
them. Don't get fooled by the name -- a dict also isn't a very good
data structure to implement an actual Chinese-English dictionary, for
example. :-)
--
--Guido van Rossum (python.org/~guido)
More information about the Python-Dev
mailing list