Problem using Random

Paul Sidorsky paulsid at home.com
Sun Oct 28 05:50:57 CET 2001


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)
>   print mylist  ## Just to check the list status after the remove()

> Is there any way that I can get the random.choice() to go through and
> exhaust all possible choices before quitting?

Try this instead:

>>> mylist = ['a','b','c','d','e','f']
>>> while mylist:
        item = random.choice(mylist)
        mylist.remove(item)
        print item
e
c
f
a
d
b

It's a bad idea to modify a list while iterating through its members using
for.  See this post for an illustration of what essentially happens when you
do:

http://groups.google.com/groups?hl=en&selm=mailman.1002044522.14637.python-list%40python.org

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid at home.com                      http://members.home.net/paulsid/




More information about the Python-list mailing list