Trying to use sets for random selection, but the pop() method returns items in order

Ben Finney ben+python at benfinney.id.au
Wed Jul 1 19:01:10 EDT 2009


Mario Garcia <Mariosky at gmail.com> writes:

> Im trying to use sets for doing statistics from a data set.
> I want to select, 70% random records from a List. I thougth set where
> a good idea so I
> tested this way:
> 
> c = set(range(1000))
> for d in range(1000):
>      print c.pop()
> 
> I was hoping to see a print out of random selected numbers from 1 to
> 1000

The ‘set’ and ‘dict’ types are unordered collections, but that doesn't
have any implication of randomness. Rather, it means that the order of
retrieval is not guaranteed to be predictable.

You can't even predict that it'll be a random order; you can't predict
(based on the Python code) *anything* about the order. Any appearance of
predictable ordering is an unreliable artefact of the implementation and
may change at any time, since the language explicitly disclaims any
specific ordering to the items.

For a random sequence, you want the ‘random’ module
<URL:http://docs.python.org/library/random>::

    >>> import random
    >>> for n in (random.randint(0, 999) for _ in range(10)):
    ...     print n
    ...
    381
    4
    471
    624
    70
    979
    110
    932
    105
    262 

-- 
 \        “When in doubt tell the truth. It will confound your enemies |
  `\   and astound your friends.” —Mark Twain, _Following the Equator_ |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list