Problem using Random

Terry Reedy tjreedy at home.com
Sun Oct 28 01:48:11 EST 2001


"Peter Hansen" <peter at engcorp.com> wrote in message
news:3BDB921E.FA7390EF at engcorp.com...
> Jeremy Whetzel wrote:
> >
> > mylist = ['a','b','c','d','e','f']
> > print mylist
> > for i in mylist:
> >   c = random.choice(mylist)
> >   print c
> >   mylist.remove(c)
> >
> > Is there any way that I can get the random.choice() to go through
and
> > exhaust all possible choices before quitting?
>
> There are many ways... :)
>
> Your problem above is in iterating over the list with 'i'.  Why
> do that, when you are not even using 'i' in the code?
>
> Try something like this instead, as a quick first attempt.
> (Note that the conditional evaluation of mylist returns false
> when the list is empty, exiting the loop.)
>
> >>> import random
> >>> mylist = ['a','b','c','d','e','f']
> >>> while mylist:
> ...     c = random.choice(mylist)
> ...     print c
> ...     mylist.remove(c)
> f
> a
> d
> b
> c
> e

Removing items from near the front of a long list takes time.  *If*
this matters, the following should be faster (when <pseudocode>
translated to Python):
...
n = len(mylist)
while mylist:
  i = <random list index, ie in [0,n-1]>
  n -= 1
  mylist[i], mylist[n] = mylist[n], mylist[i]
  c = mylist.pop()
  print c

Terry J. Reedy






More information about the Python-list mailing list