Whrandom

Tim Peters tim.one at home.com
Tue May 15 00:26:55 EDT 2001


[Duncan Smith]
> I would do the following.
>
> >>> import whrandom

DON'T!  whrandom is deprecated -- it never should have been exposed, and it's
going away someday.  Import "random" instead.

> >>> dict = {}
> >>> while len(dict.keys()) != 5:
> ...  dict[whrandom.randint(1, 1000)] = None
> ...
> >>> dict.keys()
> [247, 844, 578, 892, 244]
>
> Now I am a statistician and not a computer scientist.  I have developed
> a habit of using dictionaries (as above) rather than lists because I am
> under the impression it is more efficient than checking the current list
> for a match on each iteration.  Could any computer scientists out there
> confirm this (or point me in a more efficient direction).  Cheers.

You're correct, but it really takes a statistician to quantify this <wink>.
A failing list lookup takes len(list) comparisons, a failing dict lookup
between 1 and 2 comparisons "on average" and independent of dict size.  But
for lists this small, it doesn't make enough difference to matter.

What does matter is

    while len(dict.keys()) != 5:

dict.keys() there builds a full list of keys each time around the loop, and
that takes even longer than searching the full list.  What you want there
instead is

    while len(dict) < 5:






More information about the Python-list mailing list