#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2005
    Posts
    60
    Rep Power
    10

    Newbie question (loops)


    I have to make here a program that prints a list of words in random order. and the words cannot repeat.

    i have this

    Code:
    import random
    
    words = ["one", "two", "three", "four", "five"]
    
    for i in range(len(words)):
        words2 = words[:]
        randitem = random.choice(words2)
        print randitem
        words2.remove(randitem)
    
    input()
    But i don't know whty it doesn't work. The loop works but some words repeat, even though i remove them from the list.
  2. #2
  3. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Originally Posted by play_
    I have to make here a program that prints a list of words in random order. and the words cannot repeat.

    i have this

    Code:
    import random
    
    words = ["one", "two", "three", "four", "five"]
    
    for i in range(len(words)):
        words2 = words[:]
        randitem = random.choice(words2)
        print randitem
        words2.remove(randitem)
    
    input()
    But i don't know whty it doesn't work. The loop works but some words repeat, even though i remove them from the list.
    Your copying words each time though the loop then removing the random word from that copy .

    You could remove the line defining words2 or move it outside the loop, then just make sure you're removing from the appropriate list and your set.

    You might also want to try random.shuffle() then you can just print them normally by looping though.

    Take care,

    Mark.
    programming language development: www.netytan.com Hula

  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2005
    Posts
    60
    Rep Power
    10
    Originally Posted by netytan
    Your copying words each time though the loop then removing the random word from that copy .

    You could remove the line defining words2 or move it outside the loop, then just make sure you're removing from the appropriate list and your set.

    You might also want to try random.shuffle() then you can just print them normally by looping though.

    Take care,

    Mark.
    haha yea, i got fed up and checked the python website for other functions and tried out shuffle.

    but the book hasnt showed shuffle yet, so i wanna do it with what the book has shown. Ill try out your advice.
    Thanks!



    ::edit::

    and yes, it worked. thanks again

IMN logo majestic logo threadwatch logo seochat tools logo